我需要使用按鈕驅動的 javascript 將右對齊的 div 從一個位置移動到另一個位置。
所以頁面被渲染,外部 div 是使用position:relative;width:250px;. 內部 div 用于position:absolute;right:0px;將其放置在外部 div 的最右側。
我假設如果我的 javascript 設定外層 div 的寬度,它會改變外層 div 的寬度,而內層 div 會相對于此移動。但它不會移動(即使獲取外部 div 的寬度值確認新值已設定)。
這是否意味著一旦頁面呈現,您就不能更改 div 寬度?如果瀏覽器視窗寬度發生變化,它們可以更改,我認為這是可能的。
<div id="test" style="display:inline-block;position:relative;width:250px;">
<div style="display:inline-block;">
Some text
</div>
<div style="display:inline-block;position:absolute;right:0px;">
Some more text
</div>
</div>
<br>
<br>
<button type="button" onclick="resizeouter(500);">
Move Right
</button>
<script>
function resizeouter(newsize){
document.getElementById('test').width=newsize "px";
//alert(document.getElementById('test').width);
}
</script>
我試過有和沒有 “px”。
JSFiddle
提前致謝。
uj5u.com熱心網友回復:
你要找的是style.width:
document.getElementById('test').style.width= newsize "px";
uj5u.com熱心網友回復:
你需要添加 .style.width
https://www.w3schools.com/jsref/prop_style_width.asp
function resizeouter(elementID, newsize){
let div = document.getElementById(elementID); // current element
let currentWidth = div.offsetWidth; // current width of your element
let finalWidth = currentWidth newsize; // addition of current width newsize
div.style.width=finalWidth "px"; // set the new width for this element
//alert(document.getElementById('test').width);
// debug infos
console.log(currentWidth ' ' newsize ' = ' finalWidth);
}
<div id="test" style="display:inline-block;position:relative;width:250px;">
<div style="display:inline-block;">
Some text
</div>
<div style="display:inline-block;position:absolute;right:0px;">
Some more text
</div>
</div>
<br>
<br>
<button type="button" onclick="resizeouter('test', 500);">
Move Right
</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366127.html
標籤:javascript html 查询 css
下一篇:如何將影像堆疊在文本上方?
