gpt4 book ai didi

javascript - 两个String不能相加(+=运算)

转载 作者:行者123 更新时间:2023-11-29 21:45:59 29 4
gpt4 key购买 nike

我正在从事一个项目,让用户鼠标滚轮移动并知道它向上或向下滚动。在我的代码中,我可以上下移动。但我想将 Action 保存到一个字符串中。例如,如果用户向上向上向下滚动'mhmh' 显示返回“UUD”但现在它只是得到最后一个 Action (只是 U o D)

<script type="text/javascript">

function displaywheel(e){
var evt=window.event || e //equalize event object
var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta
//check for detail first so Opera uses that instead of wheelDelta
var mhmh = ''
var t = ''
//mhmh = (delta<=-120)? mhmh + 'D' : mhmh + 'U'
if (delta<=-120)
t = "d"
else
t = "u"

mhmh = mhmh + t
document.getElementById("wheelvalue").innerHTML= mhmh //delta returns +120 when wheel is scrolled up, -120 when down
}

var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

if (document.attachEvent) //if IE (and Opera depending on usesr setting)
document.attachEvent("on"+mousewheelevt, displaywheel)
else if (document.addEventListener) //WC3 browsers
document.addEventListener(mousewheelevt, displaywheel, false)
</script>

您可以 sample web page here .有什么问题吗?

最佳答案

问题是每次调用事件处理程序时,您都在重新定义 mhmh。这是closures的地方派上用场。将您的 mhmh 变量存储在事件处理程序上下文之外:

var mhmh = '';

function displaywheel(e){
var evt=window.event || e //equalize event object
var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta
//check for detail first so Opera uses that instead of wheelDelta

var t = ''
//mhmh = (delta<=-120)? mhmh + 'D' : mhmh + 'U'
if (delta<=-120)
t = "d"
else
t = "u"

mhmh = mhmh + t
document.getElementById("wheelvalue").innerHTML= mhmh //delta returns +120 when wheel is scrolled up, -120 when down
}

var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

if (document.attachEvent) //if IE (and Opera depending on usesr setting)
document.attachEvent("on"+mousewheelevt, displaywheel)
else if (document.addEventListener) //WC3 browsers
document.addEventListener(mousewheelevt, displaywheel, false)

关于javascript - 两个String不能相加(+=运算),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168887/

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