如何通过JavaScript动态设置图片的src属性值?
- 内容介绍
- 文章标签
- 相关推荐
本文共计401个文字,预计阅读时间需要2分钟。
设置方法:1、利用元素对象的src属性,语法:img元素对象.src=属性值;2、使用setAttribute()方法,语法:img元素对象.setAttribute('src', 属性值)。操作环境:Windows 7系统、JavaScript 1。
设置方法:1、利用元素对象的src属性,语法“img元素对象.src="属性值"”;2、利用setAttribute()方法,语法“img元素对象.setAttribute("src","属性值")”。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript设置img src值
方法1:利用元素对象的src属性
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" width="200" /> <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.src = "img/2.jpg"; } </script> </body> </html>
效果图:
方法2:利用setAttribute()方法
setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" width="200" /> <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.setAttribute("src","img/3.jpg"); } </script> </body> </html>
效果图:
本文共计401个文字,预计阅读时间需要2分钟。
设置方法:1、利用元素对象的src属性,语法:img元素对象.src=属性值;2、使用setAttribute()方法,语法:img元素对象.setAttribute('src', 属性值)。操作环境:Windows 7系统、JavaScript 1。
设置方法:1、利用元素对象的src属性,语法“img元素对象.src="属性值"”;2、利用setAttribute()方法,语法“img元素对象.setAttribute("src","属性值")”。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript设置img src值
方法1:利用元素对象的src属性
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" width="200" /> <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.src = "img/2.jpg"; } </script> </body> </html>
效果图:
方法2:利用setAttribute()方法
setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。
<!DOCTYPE html> <html> <body> <img src="img/1.jpg" width="200" /> <p id="demo">点击按钮来改变img标签的内容。</p> <button onclick="myFunction()">试一下</button> <script> function myFunction() { var img = document.getElementsByTagName("img")[0]; img.setAttribute("src","img/3.jpg"); } </script> </body> </html>
效果图:

