我在我的页面上使用jquery
,我希望当用户点击某个按钮时,图像将在主要内容出现之前显示加载1秒
这是我的代码:
<script>
$(document).ready(function(){
$("#UseractivityLog").click(function(){
$(".UserProfileLogs-cont").html("<img src='image/loading.gif'/>");
//Then for 1/2 seconds this UserProfileLogs will display
$(".UserProfileLogs").toggle();
});
$("#IdealLog").click(function(){
$(".UserProfileLogs-con").toggle();
});
});
</script>
这是我的HTML部分
<a href="#" id="UseractivityLog">Logs</a>
<div id="UserProfileLogs-cont">
<div id="IdealLog"></div>
<div id="UserProfileLogs"></div>
</div>
请相信jsfiled样本
答案 0 :(得分:1)
您有一些选择器不一致,请确保您正在观看(#
而不是.
)。
暂停时,请使用setTimout()
:
$(document).ready(function(){
$("#UseractivityLog").click(function(){
$("#UserProfileLogs-cont").html("Loading...");
setTimeout(function() {
$("#UserProfileLogs-cont").html("<img src='http://placehold.it/350x150'>");
}, 1000);
//Then for 1/2 seconds this UserProfileLogs will display
$(".UserProfileLogs").toggle();
});
$("#IdealLog").click(function(){
$("#UserProfileLogs-cont").toggle();
});
});
小提琴:https://jsfiddle.net/Lqgum8hu/
征求意见:
//然后在1/2秒内显示此UserProfileLogs
使用另一个超时:
setTimeout(function() {
// Whatever...
}, 500);
我稍微更改了一些HTML以展示示例,但是可以根据需要更改它而不更改Javascript。
答案 1 :(得分:0)
你可以等到身体准备好了:
function onReady(callback) {
var intervalID = window.setInterval(checkReady, 1000);
function checkReady() {
if (document.getElementsByTagName('body')[0] !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}
}
function show(id, value) {
document.getElementById(id).style.display = value ? 'block' : 'none';
}
onReady(function () {
show('page', true);
show('loading', false);
});
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
background-color: rgba(192, 192, 192, 0.5);
background-image: url("http://i.stack.imgur.com/MnyxU.gif");
background-repeat: no-repeat;
background-position: center;
}
这是一个演示这种技术的JSFiddle。
答案 2 :(得分:0)
您可以在setTimeout
秒后使用n
更新图片来源。
此外,您可以使用单个div
和嵌套img
来实现此目的,而无需使用单独的容器来加载图标和图像。
希望下面的代码段有用
<强> HTML 强>
<a href="#" id="UseractivityLog">Logs</a>
<div id="UserProfileLogs-cont">
<img src="">
</div>
<强> JS 强>
$(document).ready(function(){
var _gif = "http://assets.motherjones.com/interactives/projects/features/koch-network/shell19/img/loading.gif";
var _forest="http://www.discovertheforest.org/images/hero/home/6.jpg";
$("#UseractivityLog").click(function(){
$("#UserProfileLogs-cont img").attr("src",_gif);
setTimeout(function(){
$("#UserProfileLogs-cont img").attr("src",_forest);
},3000)
});
});
选中此jsfiddle