2015-07-09 27 views
0

我希望能够单击按钮并更改以%为单位给出的div值,以便在单击按钮时将div移出屏幕。更改使用Javascript给出的CSS Div位置值%

但是,下面的代码在点击按钮时不会产生结果。我非常感谢我能得到的任何建议。

function Shift() { 
 
    var x = document.getElementById("Lac"); 
 
    if (x.style.left === "0%" && x.style.top === "0%") { 
 
    x.style.left = "100%"; 
 
    x.style.top = "100%"; 
 
    } 
 
}
#Lac { 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    z-index: 2; 
 
    left: 0%; 
 
    top: 0%; 
 
    background-color: #0062FF; 
 
    transition-duration: 0.3s; 
 
}
<div id="Lac"> 
 
    <button onclick="Shift()">Button</button> 
 
</div>

+0

值得注意的是,你可能不能够简单的情况下,重新发布,如果你[在那里封锁的问题](http://meta.programmers.stackexchange.com/q/7020/31260)(你是吗?) – gnat

回答

0

解决方案1:我建议你删除if语句。它没有任何好处。

function Shift() { 
 
    var x = document.getElementById("Lac"); 
 
    x.style.left = "100%"; 
 
    x.style.top = "100%"; 
 
}
#Lac { 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    z-index: 2; 
 
    left: 0%; 
 
    top: 0%; 
 
    background-color: #0062FF; 
 
    transition-duration: 0.3s; 
 
}
<div id="Lac"> 
 
    <button onclick="Shift()">Button</button> 
 
</div>

解决方案2:添加一个类的名称,而不是所有的JavaScript。

#Lac { 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 100%; 
 
    z-index: 2; 
 
    left: 0%; 
 
    top: 0%; 
 
    background-color: #0062FF; 
 
    transition-duration: 0.3s; 
 
} 
 
#Lac.hide { 
 
    left: 100%; 
 
    top: 100%; 
 
}
<div id="Lac"> 
 
    <button onclick="this.parentNode.className='hide';">Button</button> 
 
</div>

+0

非常感谢。我非常感谢帮助。解决方案2完美运作。 – Ike10

0

不能从.style.left检索值,你需要做到以下几点:

var style = window.getComputedStyle(document.getElementById("Lac")) 
console.log(style.left); //outputs 0px 
var left = parseInt(style.left); //0 
if (!left){ 
    //do the animation 
}