[英]JavaScript change img src attribute without jQuery
How to change the src
attribute of a HTMLImageElement
in JavaScript? 如何在JavaScript中更改
HTMLImageElement
的src
属性?
I need help to convert logo.attr('src','img/rm2.png')
to vanilla JavaScript. 我需要帮助将
logo.attr('src','img/rm2.png')
为vanilla JavaScript。
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.attr('src','img/rm2.png');
}
};
You mean you want to use pure javascript? 你的意思是你想使用纯JavaScript?
This should do it: 这应该这样做:
var logo = document.getElementById('rm');
logo.src = "img/rm2.png";
So your function should look like : 所以你的功能应该是这样的:
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.src = "img/rm2.png";
}
};
Note : You could also use element.setAttribute . 注意 :您还可以使用element.setAttribute 。 BUT, see this post for more:
但是,请参阅此帖子了解更多信息:
When to use setAttribute vs .attribute= in JavaScript? 何时在JavaScript中使用setAttribute vs .attribute =?
try this...hope it works 试试这个...希望它有效
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.setAttribute('src','img/rm2.png');
}
};
So if you want to check if the size has changes and then changes back check code bellow. 因此,如果您想检查大小是否有变化,然后更改回检查代码。
window.onresize = window.onload = function () {
if (window.innerWidth < 768) {
var logo = document.getElementById('changeLeft');
logo.src = "MobileImage.png";
}else{
var logo = document.getElementById('changeLeft');
logo.src = "DesktopImage.png";
}
};
Adjust window.innerWidth to decide on your break points. 调整window.innerWidth来决定你的断点。 Hope that helps.
希望有所帮助。
我认为这只是logo.src = "img/rm2.png"
。
var logo = document.getElementById('rm');
logo.setAttribute('src', 'img/rm2.png');
Since you say you want to do this in different places of the program, I would create a function like this: 既然你说你想在程序的不同位置做这个,我会创建一个这样的函数:
function ChangeImage(image_id,path)
{
document.images[image_id].src = path
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.