Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HTML属性中的Javascript变量_Javascript_Html_Variables - Fatal编程技术网

HTML属性中的Javascript变量

HTML属性中的Javascript变量,javascript,html,variables,Javascript,Html,Variables,我知道有很多关于这方面的帖子,但我找不到我的具体问题的答案 我想让JS变量成为HTML属性的值 <script> var screenWidth = screen.width </script> <img src="images/title.png" width="VARIABLE HERE" style="margin-top: 3%"` var screenWidth=screen.width 变量这里是我希望screenWidth变量的位置。这样做最好的

我知道有很多关于这方面的帖子,但我找不到我的具体问题的答案

我想让JS变量成为HTML属性的值

<script> var screenWidth = screen.width </script> 

<img src="images/title.png" width="VARIABLE HERE" style="margin-top: 3%"`
var screenWidth=screen.width
变量这里是我希望screenWidth变量的位置。这样做最好的方法是什么

谢谢,
Ben

您不能简单地在HTML中调用JavaScript变量。您需要使用JavaScript或JQuery编写它。您可以这样做:-

 <input id="myInput" .../>
 <script>
    var myVar = "value";
    $("#myInput").attr("name", myVar);
 </script>

var myVar=“值”;
$(#myInput”).attr(“名称”,myVar);
这应该可以:

<script>var screenWidth = screen.width;</script> 
...
<img src="images/title.png" onload="this.width=screenWidth;" style="margin-top: 3%">
var screenWidth=screen.width;
...

您可以使用javascript将样式添加到如下特定元素中

脚本

document.getElementById('myImg').style.width = screen.width + "px";
Html

<img id="myImg" src="images/title.png"  style="margin-top: 3%">

这里有一个标签,给标签一个id

i、 e.

然后使用

 document.getElementById('xxx').setAttribute('width', 'somevalue')


或者使用JQuery作为另一张海报上的注释

在这种情况下,您可以使用CSS(可能通过style属性:
style=“width:100vw;”
)将宽度设置为
100vw
。这更有效、更可读,但是。

是否有遗漏?