当我执行 style.top
语句时,图像不想从顶部更改 600 像素。
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 更改图像的位置? 有绝对位置的东西,但不确定。
最佳答案
The top, right, bottom, and left properties specify the position of positioned elements. -positionMDN
您的图像元素未定位,因此使用 top、right、bottom 或 left 将无效。为了在不改变文档流的情况下定位元素(使用 fixed 或 absolute 就可以),您可以使用 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"/>
What Is Positioning?
By default, elements flow one after another in the same order as they appear in the HTML source, with each element having a size and position that depends on the type of element, the contents of the element, and the display context for the element as it will render on the page. This default flow model for HTML layout doesn't allow a high level of control over the placement of elements on the page. By applying a small set of CSS attributes to the elements that are defined for the page, CSS can control the precise position of elements by giving exact coordinates. -About Element PositioningMSDN
关于javascript - 更改 style.top 时图像不移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538193/