[英]change image use javascript DOM
<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage")= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage")= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<a href="#" onclick="changeSrc()"><b id="boldStuff" />View large image</a>
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>
這是我的編碼,單擊時需要同時更改圖像和文本。
我使用LTS,它顯示的行為document.getElementById("myImage")= "cottage_large.jpg";
參數數目錯誤或屬性分配無效。
有人可以幫忙嗎?
比安卡
您需要執行以下步驟
這樣可以解決問題
您需要更改圖像源 。
document.getElementById("myImage").src = "cottage_large.jpg";
您應該更改:-
<b id="boldStuff" />View large image
以下:
<b id="boldStuff">View large image</b>
如果您不使用結尾標記,則getElementById似乎不適用於空標記。
完整正確的來源:
<html>
<head>
<script type="text/javascript">
var curimage = "cottage_small.jpg";
var curtext = "View large image";
function changeSrc() {
if (curtext == "View large image"||curimage == "cottage_small.jpg") {
document.getElementById("boldStuff").innerHTML = "View small image";
curtext="View small image";
document.getElementById("myImage").src= "cottage_large.jpg";
curimage = "cottage_large.jpg";
} else {
document.getElementById("boldStuff").innerHTML = "View large image";
curtext = "View large image";
document.getElementById("myImage").src= "cottage_small.jpg";
curimage = "cottage_small.jpg";
}
}
</script>
</head>
<body>
<!-- Your page here -->
<h1> Pink Knoll Properties</h1>
<h2> Single Family Homes</h2>
<p>
Cottage:<strong>$149,000</strong><br/>
2 bed, 1 bath, 1,189 square feet, 1.11 acres <br/><br/>
<a href="#" onclick="changeSrc()"><b id="boldStuff">View large image</b></a>
</p>
<p><img id="myImage" src="cottage_small.jpg" alt="Photo of a cottage" /></p>
</body>
</html>
KooiInc是正確的。 但是這種說法有一個問題。
IE6將不接受document.getElementById(“ myImage”)。src 。
所以我建議你像這樣使用jQuery。
$('#myImage')。attr(“ src”,“新的源路徑”);
更新 :
@CMS:請檢查我在說什么。
好吧,我想這里有一個可怕的誤會。 據我所知,IE6從來不支持使用“ .src =”技術直接更改圖像源。 如果我不能使用jquery,我總是使用以下技術來實現。
document.getElementById('ImageId').style.cssText="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='newPath');";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.