簡體   English   中英

更改style.top時圖像不動

[英]Image not moving when style.top is changed

當我執行style.top語句時,圖像不想從頂部更改600 px。

 document.getElementById("testing").onclick = function(event){ document.getElementById("image").width=400; document.getElementById("image").style.top = "600px"; } 
 #testing{ color:blue; } 
 <p id="testing"> aewrfafffffffffffffffacvfav </p> <img id="image" src="katakana.jpg" alt="nothing" width="300"/> 

據我了解,這應該起作用。 我不知道這是怎么回事。 簡而言之,如何使用JavaScript更改圖像的位置? 有絕對立場的事情,但不確定。

top屬性本身絕對不執行任何操作。 元素也需要定位。 例如, position: relativeposition: absolute

top,right,bottom和left屬性指定定位元素的位置。

來源: https//developer.mozilla.org/en-US/docs/Web/CSS/position

單擊該段落后,圖像相對於容器定位並且top屬性更改的示例:

 document.getElementById("testing").onclick = function(event) { document.getElementById("image").style.top = "100px"; } 
 .container { position: relative; } img { position: absolute; width: 400px; } 
 <div class="container"> <p id="testing">aewrfafffffffffffffffacvfav</p> <img id="image" src="http://lorempixel.com/g/400/200/" /> </div> 

top,right,bottom和left屬性指定定位元素的位置。 - 位置MDN

您的圖片元素定位,因此使用top,right,bottom或left無效。 為了在不更改文檔流的情況下定位元素(使用固定或絕對操作會如此),可以使用position: relative; 它將保留在文檔流中,而現在被認為是“定位”。

 document.getElementById("testing").onclick = function(event){ document.getElementById("image").width=400; document.getElementById("image").style.top = "600px"; } 
 #testing{ color:blue; } #image{ position: relative; /* <- positioning */ } 
 <p id="testing"> aewrfafffffffffffffffacvfav </p> <img id="image" src="katakana.jpg" alt="nothing" width="300"/> 

什么是定位?
默認情況下,元素按照它們在HTML源代碼中出現的順序依次流動,每個元素的大小和位置取決於元素的類型,元素的內容以及該元素的顯示上下文。它將呈現在頁面上。 HTML布局的默認流模型不允許對頁面上元素的位置進行高度控制。 通過將少量CSS屬性應用於為頁面定義的元素,CSS可以通過提供精確的坐標來控制元素的精確位置。 - 關於元素定位 MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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