是否可以像这样设置元素宽度:
<img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/>
其中 getScreenSize() 是一个 javascript 函数。
function getScreenSize()
{
var res = {"width": 630, "height": 460};
if (document.body)
{
if (document.body.offsetWidth) res["width"] = document.body.offsetWidth;
if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
}
if (window.innerWidth) res["width"] = window.innerWidth;
if (window.innerHeight) res["height"] = window.innerHeight;
alert( res['width'] );
return res;
}
或者我是否必须在 javascript 函数中更改 img 的宽度?
function changeImgWidth( img )
{
img.offsetRight = getScreenWidth()['width'] + "px";
}
最佳答案
你不能用那种语法来做,不。你可以使用 document.write
这样做,但我怀疑你最好在 DOM 加载后这样做,因为我认为你的 getScreenSize
到那时函数可能不会报告正确的结果(但它可能,你必须测试)。
用document.write
来做:
<script>
document.write('<img id="backgroundImg" src="images/background.png" alt="" width="' + getScreenSize()['width'] + '" height="1100px"/>');
</script>
要在加载 DOM 后执行此操作,请将其放在页面的最后,就在结束之前 </body>
标签:
<script>
document.getElementById('backgroundImg').width = getScreenSize()['width'];
</script>
在这两个例子中,我都坚持使用 width
属性(请注意,您不要在 width
属性中使用单位后缀“px”)。但您可能会考虑使用 CSS width
属性(您将使用后缀)。
不过,退一步说,与其依赖 JavaScript 来设置宽度,我建议尝试使用 CSS 来设置宽度。您可以使用 style='width: 100%'
使图像成为其容器宽度的 100%在标签内或:
#backgroundImg {
width: 100%;
}
...在样式表中。
关于javascript - 使用 javascript 立即设置 HTML 元素宽度属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6235391/