簡體   English   中英

使用Java更改以%為單位給出的CSS Div位置值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM