这是一个通知代码,我想把它放在屏幕中间。但是首先点击它不在中间,在第二次点击它显示我的预期。
我认为这是一个高度和错误的错误宽度。
(没有定义css的帮助)
var showNotice = function(txt,mode){
var mode = mode || 0;
var width = $(window).width();
var height = $(window).height();
$("body").append("<span id='notice'>"+txt+"</span>");
var noticeW = $("body #notice").outerWidth();
var noticeH = $("body #notice").outerHeight();
$("body #notice").css({
"position":"absolute",
"z-index":"1000",
"background":"black",
"color":"white",
"padding":"20px",
"cursor":"pointer",
"border-radius":"8px",
"box-shadow":"0 0 15px rgba(0,0,0,0.6)",
"top":(height/2)-(noticeH/2)+"px",
"left":(width/2)-(noticeW/2)+"px",
"display":"none"
}).fadeIn();
$(document).on("click","body #notice",function(){
$("body #notice").fadeOut(1000,function(){
$(this).remove();
});
});
if(mode === 0){
setTimeout(function(){
$("body #notice").fadeOut(1000,function(){
$(this).remove();
});
},5000);
}
} // ----- showNotice() -----
HTML
<button onclick="showNotice('some text',1)">
Click
</button>
答案 0 :(得分:2)
这是因为当您获得#notice
outerHeight
和outerWidth
时,它没有宽度或高度,或任何其他CSS样式,请尝试这: DEMO
var showNotice = function(txt,mode){
var mode = mode || 0;
var width = $(window).width();
var height = $(window).height();
$("body").append("<span id='notice'>"+txt+"</span>");
$("body #notice").css({
"position":"absolute",
"z-index":"1000",
"background":"black",
"color":"white",
"padding":"20px",
"cursor":"pointer",
"border-radius":"8px",
"box-shadow":"0 0 15px rgba(0,0,0,0.6)"});
var noticeW = $("body #notice").outerWidth();
var noticeH = $("body #notice").outerHeight();
$("body #notice").css({
"top":(height/2)-(noticeH/2)+"px",
"left":(width/2)-(noticeW/2)+"px",
"display":"none"
}).fadeIn();