简体   繁体   中英

css(“position”) returns undefined when window resize

I've got the following code to catch the browser resize event.

 window.onresize = function(){
 var style = $('#button-selection').position();
 if(style == "relative"){
 $("#button-section").css("position"," ");
 }else if(style == "fixed"){
    $("#button-section").css("position","relative");
 }              
 };


 window.onresize = function(){
            var style = $('#button-selection').css('position');
            if(style == "relative"){
                $("#button-section").css("position"," ");
            }else if(style == "fixed"){
                $("#button-section").css("position","relative");
            }               
        };

The style returns undefined. I'm running this when the document is ready. I tried using window ready but the result is the same. both the above methods return undefined!

Change this:

var style = $('#button-selection').position();

to this:

var style = $('#button-selection').css('position');

.position() is used to get the coordinates of the element.

From the docs:

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.


Update:

Use $(window).resize() instead. i am having a test case scenario here: in this fiddle .

$(window).resize(function () {
  var style = $('button').css('position');
  if (style == "relative") {
    alert('relative');
  } else if (style == "fixed") {
    alert('fixed');
  }
});

jQuery docs say .position() is:

Description: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

you should use:

 var style = $('#button-selection').css('position');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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