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

时间:2014-06-07 08:12:38

标签: javascript jquery html css

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

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位置是否固定。谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

$(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 combine .ready and .resize

答案 1 :(得分:0)

您可以使用:

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