你可以这样做,它也会允许不同的文件名。
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
搭配点评:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
' “png格式”'是不是该元素的'id'的一部分。不要添加它;只要查找'“imgCh”+ i'。 –
你是什么意思,你只是半途而废?您的元素ID不匹配(您包含'.png'),并且您的图片源不同(以'/开头,然后更改为相对位置),因此需要多次点击才能启动。此外,您可以考虑在图片的顶部添加一个绿色滤镜以减少网络使用,而不是加载完整的单独图片。 –
我可以在jQuery中进行更改吗? – Rahul