我基本上有这个链接,当我点击它时,我希望在它上面显示一个图像。使用 javascript 我怎样才能做到这一点?
<a> click me </a>
CSS:
a.clicked
{
/*what goes here?*/
}
最佳答案
添加新的图像元素非常简单:
// Append an image with source src to element
function appendImage(element, src, alt) {
// DOM 0 method
var image = new Image();
// DOM 1+ - use this or above method
// var image = document.createElement('img');
// Set path and alt properties
image.src = src;
image.alt = alt;
// Add it to the DOM
element.appendChild(image);
// If all went well, return false so navigation can
// be cancelled based on function outcome
return false;
}
所以在 A 元素中:
<a onclick="appendImage(this, 'foo.jpg', 'Picture of foo');">Add an image</a>
如果 A 是链接并且您希望取消导航,则返回函数返回的任何内容。如果该函数不返回 false,则将跟踪该链接并应提供等效功能:
<a href="link_to_picture or useful page" onclick="
return appendImage(this, 'foo.jpg', 'Picture of foo');
">Add an image</a>
关于javascript - 如何使用 javascript 将图像添加到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6119315/