求助:如何仅用JavaScript实现鼠标悬停切换宝可梦卡牌图片?
问题排查:精灵球卡牌悬停切换图片失效
你的悬停切换功能失效的核心原因是作用域问题:createBoard循环里定义的const card是局部变量,hoverPokeball和unhoverPokeball函数无法访问到这个变量,导致setAttribute操作没有作用到正确的图片元素上。
修复方案
有两种简单的修复方式,任选其一即可:
方式1:使用this关键字
事件触发时,this会指向触发该事件的img元素,直接用它修改src:
function hoverPokeball() { this.setAttribute('src', 'src/images/pokeballMid.png') } function unhoverPokeball() { this.setAttribute('src', 'src/images/pokeballOpen.png') }
方式2:使用事件对象的target属性
让函数接收事件参数,通过event.target获取触发事件的元素:
function hoverPokeball(event) { event.target.setAttribute('src', 'src/images/pokeballMid.png') } function unhoverPokeball(event) { event.target.setAttribute('src', 'src/images/pokeballOpen.png') }
额外优化(可选)
如果你的游戏里卡牌有翻转状态(比如已经翻开显示宝可梦),可以加个判断,只在卡牌处于打开精灵球状态时触发悬停切换:
function hoverPokeball() { if (this.src.includes('pokeballOpen.png')) { this.setAttribute('src', 'src/images/pokeballMid.png') } } function unhoverPokeball() { if (this.src.includes('pokeballMid.png')) { this.setAttribute('src', 'src/images/pokeballOpen.png') } }
内容的提问来源于stack exchange,提问作者user15147717
相关产品推荐
相关产品推荐

