繁体   English   中英

如果窗口调整大小,jQuery检查元素css属性

[英]jQuery check an element css property if the window resize

如何为此添加窗口调整大小功能?

jQuery(document).ready(function($){         
    var $MyDiv1 = $('#mydiv1');
        if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
           console.log ( '#mydiv1 is fixed' );      
        } else {    
           console.log ( '#mydiv1 is not fixed' );      
        }       
 });

如果我在调整大小后刷新页面,这项工作。 我想在窗口调整大小时检查MyDiv1位置是否固定。 谢谢你的帮助。

$(document).ready(myfunction);
$(window).on('resize',myfunction);

function myfunction() {
    var $MyDiv1 = $('#mydiv1');
    if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
      console.log ( '#mydiv1 is fixed' );      
    } else {    
      console.log ( '#mydiv1 is not fixed' );      
    }   
}

另一种技术是.trigger()在另一个内部发生一个事件:

$(window).on('resize',function() {
    var $MyDiv1 = $('#mydiv1');
    if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
      console.log ( '#mydiv1 is fixed' );      
    } else {    
      console.log ( '#mydiv1 is not fixed' );      
    }  
});
$(document).ready(function() {
    $(window).trigger('resize');
});

如果您将代码放在页面底部以避免需要$(document).ready ,它会变得更简单:

$(window).on('resize',function() {
    var $MyDiv1 = $('#mydiv1');
    if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
      console.log ( '#mydiv1 is fixed' );      
    } else {    
      console.log ( '#mydiv1 is not fixed' );      
    }  
}).trigger('resize');

参考: jQuery结合.ready和.resize

您可以使用:

$(window).on('resize', function(){
 //code here
});

使用javascript:

window.onresize = function() {
 //code here
}

完整代码:

function divreset(){ var $MyDiv1 = $('#mydiv1');
    if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
       console.log ( '#mydiv1 is fixed' );      
    } else {    
       console.log ( '#mydiv1 is not fixed' );      
    }
}
jQuery(document).ready(function($){         
  divreset();
});
window.onresize = function() {
  divreset();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM