开发者

Put inline JavaScript in the head

The following code works:

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

But the problem is you have to repeat the inline JavaScript for all img tags. I tried to put the script in the head to no avail:

<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="11开发者_开发技巧3" alt="klematis"
onmouseover="getElements()"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />

</body>
</html>

Everything seems right to me, but it doesn't work.

Many thanks for any help!

Mike


document.getElementsByTagName returns a collection (which is a lot like an array), not an HTMLElementNode. Its members have a style property, but it doesn't have one of its own, and you can't distinguish the element on which the event happened from any other.

A step in the right direction would be:

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

and then onmouseover="makeSolid(this)"

A further step in the right direction would be to use unobtrusive JavaScript and attach the events using JS instead of using intrinsic event attributes. Due to differences between browsers, using an event handling library to iron out the differences would be wise.

Since this depends on JS, the * initial* styling should be withheld until JS is confirmed to be on. Setting document.body.className = 'js' and then using .js ... as a descendent selector in each CSS ruleset is a popular way to do this.

Since this appears to be simply presentational, a further improvement would be to forget about JavaScript entirely and just do it using CSS:

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

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


Pass a reference to the element into the function, using this:

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

Called like this:

onmouseover="getElements(this)"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜