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

jQuery check an element css property if the window resize

本文关键字:检查 元素 css 属性 jQuery 窗口 调整 如果      更新时间:2023-09-26

如何添加窗口大小调整函数?

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();
}