[英]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.