满足条件时不会触发事件

时间:2015-12-19 03:00:59

标签: javascript html

我编写了一个脚本,当窗口被挤压到某个水平长度时,会将float值从right切换到left

function switchMedia(){
    if(w < 1050){
        document.getElementById("secondPic").style.cssFloat = "left";
    document.getElementById("secondPic").style.marginLeft = "1.5vh";
    }
    if(w > 1050){
        document.getElementById("secondPic").style.cssFloat = "right";
    }
  } 
}

听众在这里:

initialize();

function initialize(){
    addEventListener("resize",switchMedia,false);
    switchMedia();

}

奇怪的是它适用于我输入的w的第一个值,但是一旦切换到1050,浮点值就不会改变。

1 个答案:

答案 0 :(得分:0)

您需要更新w变量

http://jsbin.com/fivove/1/

function switchMedia(){
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if(w < 1050){
    document.getElementById("secondPic").style.float = "left";
    document.getElementById("secondPic").style.marginLeft = "1.5vh";
  }
  if(w >= 1050){
    document.getElementById("secondPic").style.float = "right";
  }
} 


function initialize(){
  window.addEventListener("resize",switchMedia,false);
  switchMedia();

}

initialize();

https://stackoverflow.com/a/28241682/383904

此外,请勿在DOM中搜索两次元素,特别是不要调整大小:

http://jsbin.com/fivove/2/

var secPic = document.getElementById("secondPic"); // Cache your element! 
// It's too expensive to lookup th whole DOM for a single element on resize

function switchMedia(){
  var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var isSmall = w < 1050;
  secPic.style.float      = isSmall ? "left" : "right";
  secPic.style.marginLeft = isSmall ? "0"    : "1.5vh";

} 

function initialize(){
  window.addEventListener("resize",switchMedia,false);
  switchMedia();
}

initialize();