gpt4 book ai didi

javascript - onmouseover -mouseout 图像

转载 作者:行者123 更新时间:2023-12-03 07:09:45 26 4
gpt4 key购买 nike

我怎么能有两张图片,一张在鼠标悬停时显示,一张在鼠标移出时隐藏?

<td id="img" onmouseover="showIt(this.src)" onmouseout="hideIt()" src="image1.jpg " src="default.jpg">my box" </td>


function showIt(imgsrc)
{
document.getElementById('img').src=imgsrc;
}

function hideIt()
{
document.getElementById('img').src="default.png";
}

最佳答案

您也可以仅使用 CSS 来实现此目的。请注意,在 DOM 操作方面,CSS 总是比 JS 快。

另外如评论所述,您必须改用 img 标签

CSS 方法

.hover-toggle {
content: url('https://reputationtoday.in/wp-content/uploads/2019/11/110-1102775_download-empty-profile-hd-png-download.jpg');
width: 100px;
height: 100px;
border: 1px solid gray;
}

.hover-toggle:hover {
content: url('https://img.favpng.com/0/8/3/user-profile-computer-icons-internet-bot-png-favpng-92SBLLR7CwZpN8Vm6MUsuU4Sd.jpg')
}
<img class='hover-toggle'>


正如 @StackSlave 正确评论的那样, hover 在移动设备上会有问题。

:hover is a problem on mobile. I would use Element.onmouseenter and Element.ontouchstart and Element.onmouseleave and Element.ontouchend instead.

JS 方法

function registerEvents() {
const img = document.getElementById('img');
img.addEventListener('mouseenter', showIt)
img.addEventListener('mouseleave', hideIt)
}

function showIt() {
this.src = 'https://img.favpng.com/0/8/3/user-profile-computer-icons-internet-bot-png-favpng-92SBLLR7CwZpN8Vm6MUsuU4Sd.jpg';
}

function hideIt() {
this.src = 'https://reputationtoday.in/wp-content/uploads/2019/11/110-1102775_download-empty-profile-hd-png-download.jpg';
}

function initialize() {
const img = document.getElementById('img');
// set default state
hideIt.call(img)

// Register events
registerEvents()
}

initialize()
#img {
width: 100px;
height: 100px;
border: 1px solid gray;
}
<img id='img'>

引用:

关于javascript - onmouseover -mouseout 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65067625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com