繁体   English   中英

将内联 JavaScript 放入头部

[英]Put inline JavaScript in the head

以下代码有效:

<html>
<head>
<style type="text/css">
img
{
opacity:0.4;
filter:alpha(opacity=40);
}
</style>
</head>
<body>

<img src="http://www.w3schools.com/Css/klematis.jpg" width="150" height="113" alt="klematis"
onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />

<img src="http://www.w3schools.com/Css/klematis2.jpg" width="150" height="113" alt="klematis"
onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />

</body>
</html>

但问题是您必须为所有 img 标签重复内联 JavaScript。 我试图把脚本放在头上,但无济于事:

<html>
<head>
<style type="text/css">
img
{
opacity:0.4;
filter:alpha(opacity=40);
}
</style>
<script type="text/javascript">
function getElements()
  {
  var x=document.getElementsByTagName("img");
  x.style.opacity=1; x.filters.alpha.opacity=100;
  }
</script>
</head>
<body>

<img src="http://www.w3schools.com/Css/klematis.jpg" width="150" height="113" alt="klematis"
onmouseover="getElements()"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />

<img src="http://www.w3schools.com/Css/klematis2.jpg" width="150" height="113" alt="klematis"
onmouseover="getElements()"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />

</body>
</html>

一切对我来说似乎都是正确的,但它不起作用。

非常感谢您的帮助!

麦克风

document.getElementsByTagName返回一个集合(很像一个数组),而不是 HTMLElementNode。 它的成员有一个style属性,但它没有自己的属性,而且你无法区分发生事件的元素和其他元素。

朝着正确方向迈出的一步是:

function makeSolid(element) {
  element.style.opacity=1; x.filters.alpha.opacity=100;
}

然后onmouseover="makeSolid(this)"

朝着正确方向迈出的进一步一步是使用不显眼的 JavaScript并使用 JS 而不是使用固有事件属性附加事件。 由于浏览器之间的差异,使用事件处理库来消除差异是明智的。

因为这取决于 JS,所以 * initial* 样式应该被保留,直到 JS 被确认打开。 设置document.body.className = 'js'然后使用.js...作为每个 CSS 规则集中的后代选择器是一种流行的方法。

由于这似乎只是展示性的,进一步的改进是完全忘记 JavaScript 并使用 CSS 来完成:

img {
  opacity:0.4;
  filter:alpha(opacity=40);
}

img:hover {
  opacity:1;
  filter:alpha(opacity=100);
}

使用this方法将元素的引用传递到 function 中:

function getElements(x) {
   x.style.opacity=1; x.filters.alpha.opacity=100;
}

像这样调用:

onmouseover="getElements(this)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM