[英]How to move/position DIV container by changing CSS values using Javascript?
[英]Changing CSS Div Position Value Given in % Using Javascript
我希望能够单击一个按钮并更改以%给出的div值,以在单击按钮时将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>
解决方案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:添加className而不是所有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>
您无法从.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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.