[英]how to change attribute in html using javascript
這是我的代碼,那么如何更改width屬性?
<html>
<head>
<script type="text/javascript">
document.getElementById("cpul").src="hello.jpg";
</script>
</head>
<body>
<img src="hi.jpg" width="100" height="100" id="cpul">
</body>
</html>
以上是失敗的,圖像完全沒有變化!!
但是為什么當我使用這個代碼(從其他網站復制)時,圖像就會發生變化
<html>
<head>
<title>JS DD Function</title>
<script type="text/javascript">
function jsDropDown(imgid,folder,newimg)
{
document.getElementById(imgid).src="http://www.cookwithbetty.com/" + folder + "/" + newimg + ".gif";
}
</script>
</head>
<body>
<table>
<tr>
<td>
Foods: <select name="food" onChange="jsDropDown('cful','images',this.value)">
<option value="steak_icon">Steak</option>
<option value="salad_icon">Salad</option>
<option value="bread_icon">Bread</option>
</select><br />
</td>
<td>
<img src="http://www.cookwithbetty.com/images/steak_icon.gif" id="cful">
</body>
</html>
您的代碼無法正常工作的最可能原因是它在元素存在於DOM之前執行。 您應該將代碼設置為在窗口load
事件上運行,或者將其放在文檔的末尾,以確保在您嘗試訪問它之前該元素存在。
<html>
<head>
<title>Foo</title>
</head>
<body>
<img src="hi.jpg" width="100" height="100" id="cpul">
<script type="text/javascript">
document.getElementById("cpul").src="hello.jpg";
</script>
</body>
</html>
放入窗口的onload
事件,因此在加載圖像html代碼之前代碼不會執行。 並使用width
屬性設置寬度。
<html>
<head>
<title>Change my image width</title>
<script type="text/javascript">
window.onload = function() {
var myImage = document.getElementById("cpul");
myImage.src = "hello.jpg";
// change width
myImage.width = 200;
};
</script>
</head>
<body>
<img src="hi.jpg" width="100" height="100" id="cpul">
</body>
</html>
您正在嘗試在尚未創建該元素時訪問DOM元素。 將script
標記移動到頁面底部(就在關閉body
之前)。
至於“改變圖像的寬度”。 獲得圖像后(通過document.getElementById
),只需設置它的width
屬性:
var myImg = document.getElementById ( 'imgsid' );
myImg.width = 100;
在您的第一個示例中,JavaScript正在立即執行。 在此階段,仍然會解析文檔,並且DOM中不存在具有指定標識的元素。
在第二個示例中,JavaScript正在執行以響應change
事件,該change
事件在元素存在之前不會觸發(好吧,除非有人使用鼠標非常快)。
您需要延遲JavaScript調用,直到元素存在之后:
<script>
移動到<img>
load
)。 你提到寬度,如果你只是在大於某個特定寬度的情況下調整圖像大小后,你可以使用圖像本身的onload
事件:
<img src="hi.jpg" id="cpul" onload="if (this.width > 100) this.width = 100;" />
這將使圖像大小調整為100像素寬度(和相應的高度),只要它大於100,否則它不會改變任何東西,即它會使圖像更小但不會更大。
如果您的意思是通過代碼更改圖像源,則只需要其他答案。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.