我编写了一个脚本,当窗口被挤压到某个水平长度时,会将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,浮点值就不会改变。
答案 0 :(得分:0)
您需要更新w
变量
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中搜索两次元素,特别是不要调整大小:
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();