javascript - 更改 style.top 时图像不移动

标签 javascript html css

当我执行 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/

相关文章:

javascript - 一次迭代两个数组的jquery每个循环

javascript - 在一个容器中我有文本和 img 标签,我怎样才能只用 js 或 jquery 获取文本

JavaScript 在按键上更改图像

javascript - 如何使用多次css transform属性?

javascript - 如何选择,聚焦文本区域?

html - 如何将下拉菜单,菜单向左移动?

javascript - 将 HTML 表导出到 XLS 时不显示特殊字符

javascript - 将选项值绑定(bind)到 AngularJS 中的 ng-model

javascript - 如何在嵌套的 Json 中使用 angularjs 进行过滤

javascript - Jquery load() 挂起