这是用于通知的代码,我想将其放在屏幕中间。但在第一次单击时,它不在中间,在第二次单击时,它显示了我所期望的。
我认为这是高度和宽度的错误。
(没有定义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>


JSfiddle

最佳答案

这是因为到#notice outerHeightouterWidth时,它没有宽度或高度或任何其他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();

09-25 17:04
查看更多