简体   繁体   English

使用Java更改以%为单位给出的CSS Div位置值

[英]Changing CSS Div Position Value Given in % Using Javascript

I want to be able to click a button and change a div value given in % to move the div off screen at the click of a button. 我希望能够单击一个按钮并更改以%给出的div值,以在单击按钮时将div移出屏幕。

However, the code below produces no result when the button is clicked. 但是,单击该按钮时,下面的代码不会产生任何结果。 I really appreciate any advice I can get. 我真的很感谢我能得到的任何建议。

 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> 

Solution 1: I suggest you remove the if-statement. 解决方案1:建议您删除if语句。 It doesn't do any good. 它没有任何好处。

 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> 

Solution 2: Add a className instead of all that JavaScript. 解决方案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> 

You cannot retrieve the value from .style.left you need to do the following: 您无法从.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.

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