我有一些 javascript 来设置 img 元素的 offsetLeft 属性。但是我的 javascript 没有移动 HTML 元素,你认为我可以做些什么来让它向左移动?在这种情况下,我最容易将元素定位在 javascript 而不是 css 中。
当它应该(它显示居中)时不会向左移动的 img 具有 id“headerImg”:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Kamalei - Home Page</title>
<style type="text/css">
<!--
body { text-align: center; min-width: 1200px; }
#backgroundImg { z-index: -1; position: absolute; left: 0px; top: 0px; }
#heading { height: 300px; }
#main { margin: 0 auto; }
#navBar { display: inline; height: 700px; width: 200px; z-index: 1; position: relative; }
#content { display: inline; height: 700px; width: 800px; padding: 20px; padding-left: 30px; }
#headingImg { left: 0px; }
#navBarImg { position: relative; z-index: 0; padding-right: -5px; margin-right: -5px; }
-->
</style>
</head>
<body>
<div id="heading">
<!-- This image will not move to the left when I call the below javascript -->
<img id="headingImg" src="images/logoWritting.png" alt="Kamalei Childrens Centre" width="600px" height="240px"/>
</div>
<div id="main">
<div id="navBar">
<img id="navBarImg" src="images/navBackground.png" alt="" width="200px" height="700px"/>
</div>
<div id="content">
</div>
</div>
<img id="backgroundImg" src="images/background.png" alt="" width="100%" height="1100px"/>
<script type="text/ajavscript">
<!--
var CONTENT_WIDTH = 1000;
function getScreenSize()
{
var res = {"width": 630, "height": 460};
if ( parseInt(navigator.appVersion)>3 )
{
res["width"] = screen.width;
res["height"] = screen.height;
}
else if ( navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled() )
{
var jToolkit = java.awt.Toolkit.getDefaultToolkit();
var jScreenSize = jToolkit.getScreenSize();
res["width"] = jScreenSize.width;
res["height"] = jScreenSize.height;
}
return res;
}
document.getElementById("headingImg").style.left = ((getScreenSize()['width']/2)-(CONTENT_WIDTH/2))+"px";
-->
</script>
</body>
</html>
最佳答案
设置 .style.left
和 position:absolute
,而不是 offsetLeft
。或者,更改 .style.marginLeft
。 offsetLeft
是只读属性。
关于javascript - 使用 javascript : it wont move 定位 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6247980/