Javascript 单击时更改图像的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7455893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
change the position of image on click
提问by niko
<html>
<head>
<script type="text/javascript">
function changepic()
{
document.getElementById("demo").style.top=2000;
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<div id="demo">
<img src="./omna.jpg" style="position:absolute; left: 400; top: 100; width: 200; height: 200;"/>
</div>
<button type="button" onclick="changepic()">change pic</button>
</body>
</html>
Why im unable to change the position of picture whats going wrong ?
为什么我无法改变图片的位置是怎么回事?
<img id="demo"> ' google says it works
I dont know but the above html page isnt working I wanted to change the position of an image when I click the button, please help me with these. Im using google chrome
我不知道,但上面的 html 页面不起作用我想在单击按钮时更改图像的位置,请帮助我解决这些问题。我使用谷歌浏览器
<img onclick="somefunc()"> can I set function onclick to image also? right?
But its not working please help me with the html Code!
但它不起作用请帮助我使用 html 代码!
采纳答案by Clive
You're trying to set the top
of an element with the id demo
, which is a <div>
. I assume that div doesn't have position:absolute
set on it so won't move anywhere, and I guess you want the <img>
to move and and not the <div>
anyway. If you remove the id from the <div>
and add it to the <img>
(like in your second piece of code above) you shouldn't have any problems. This code should work:
您正在尝试top
使用 id设置元素的demo
,即<div>
。我假设 div 没有position:absolute
设置它,所以不会移动到任何地方,我猜你想要<img>
移动而不是<div>
无论如何。如果您从 中删除 id<div>
并将其添加到<img>
(就像在上面的第二段代码中一样),您应该不会有任何问题。此代码应该工作:
<html>
<head>
<script type="text/javascript">
function changepic()
{
document.getElementById("demo").style.top=2000 + "px";
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<div>
<img id="demp" src="./omna.jpg" style="position:absolute; left: 400; top: 100; width: 200; height: 200;"/>
</div>
<button type="button" onclick="changepic()">change pic</button>
</body>
</html>
回答by Ash Burlaczenko
You setting the inline style of the imageand then setting the top
of the div. Either do one or the other. Or better still just remove the div, add an id
to your and set it's style.
您设置图像的内联样式,然后设置top
div 的样式。要么做一个,要么做另一个。或者最好还是删除 div,添加一个id
到你的并设置它的样式。
<img id="image" src="./omna.jpg" style="position:absolute; left: 400; top: 100; width: 200; height: 200;" />
document.getElementById("image").style.top=2000;