javascript - 使用 javascript 立即设置 HTML 元素宽度属性

标签 javascript html css

是否可以像这样设置元素宽度:

<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/

相关文章:

javascript - 为什么JavaScript中常见 "return this"这样的配置函数?

javascript - ES6 覆盖父方法

javascript - 是的,多个复选框的验证

javascript - 如何在jquery中取消选中嵌套复选框并保留当前单击的复选框?

javascript - 如何添加动态表单元素但保留其值(JS)

html - 使用 pandoc for html/pdf/docx 在 markdown 中正确调整 PNG 图像的大小

javascript - JQuery 切换和删除 css 类

javascript - CodeMirror - 检查光标是否位于行尾

javascript - YouTube 嵌入式视频无法在 IE8 的模态窗口中播放

javascript - 如何在 Div 中堆叠和隐藏图像以便在它们之间设置动画(无 float )