将鼠标滚轮事件捕获为本机HTML属性

时间:2017-05-15 17:39:46

标签: javascript html css mousewheel

我即将开始使用mousewheel事件,但我在网上找到的唯一一件事就是使用addEventListener()。我想要检测是否使用本机HTML和CSS。换句话说,我正在寻找类似的东西:

<span id='fooBar' onmousewheel='alert("fooBar")'></span>

我正在动态创建跨度并将它们注入到DOM中,如果我不必运行javascript就可以更好地工作。每一个其他事件,我似乎可以在本地工作,但不是鼠标轮。这可能吗?

5 个答案:

答案 0 :(得分:3)

您仅查找对addEventListener()的引用的原因是因为这是 standard 并且正确的方法(看来onmousewheel isn'甚至在Firefox中支持)。

虽然可以使用你在问题中显示的代码(在支持它的浏览器中)使用它(但是你的span为空,所以你不能用它启动事件,因为元素赢了没有任何渲染的大小)我在下面有一个例子,内联HTML事件处理属性的使用回溯到我们有标准之前的时间,不应该使用。 Here's a link 我的另一个答案解释了原因。

<span id='fooBar' onmousewheel='alert("fooBar")'>Use the mousewheel while mouse is over this</span>

答案 1 :(得分:1)

内联与委托

在演示中,A端使用标准addEventListener并注册wheel事件,该事件取代了已弃用的mousewheel事件。使用addEventListener不仅是标准,而且如果使用event delegation则效率最高。

使用onwheel作为属性事件的支持有限,因为使用任何属性事件都是非标准的并且不鼓励使用。尽管如此,我还是包含了B方,它使用了已弃用的非标准onmousewheel事件作为属性内联事件处理程序。因为它是一个笨拙的<span>,我在使用所有三个引号的字符串上使用insertAdjacentHTML(即'",`)。在嵌套引号的第二级使用了字符串文字,它非常混乱。

请参阅此post,了解如何在事件委派中使用事件对象属性。

详情在演示

中发表了评论

演示

// Reference the buttons 
const btnA = document.getElementById('addA');
const btnB = document.getElementById('addB');

// Reference the parent nodes
const secA = document.querySelector('section:first-of-type');
const secB = document.querySelector('section:last-of-type');

// Register the click event on buttons
btnA.addEventListener('click', addNodeA, false);
btnB.addEventListener('click', addNodeB, false);

/* Register the wheel event on section A 
|| which is the parent node of the wheeled
|| nodes. Event delegation involves one 
|| event handler for multiple event targets.
|| This is far more efficient than multiple 
|| inline event handlers.
*/
secA.addEventListener('wheel', markNode, false);

let cnt = 0;

/* Add node A to section A
|| ex. <span id="A1" class="A">A1</span>
*/
function addNodeA(e) {
  cnt++;
  var nodeA = document.createElement('span');
  nodeA.id = 'A' + cnt;
  nodeA.textContent = nodeA.id;
  nodeA.className = 'A';
  secA.appendChild(nodeA);
  return false;
}

/* Add node B to section B
|| ex. <span id="B3" class="B" onmousewheel="this.style.outline = `5px dashed red`">B3</span>
*/
function addNodeB(e) {
  cnt++;
  /* This string is wrapped in single quotes,
  || double quotes for the attributes values,
  || and backticks for the property value of
  || an attribute value. Very messy, confusing,
  || and inefficient.
  */
  var nodeB = '<span id="B' + cnt + '" class="B" onmousewheel="this.style.outline = `5px dashed red`">B' + cnt + '</span>';

  // insertAdjacentHTML is innerHTML on steroids
  secB.insertAdjacentHTML('beforeend', nodeB);
  return false;
}

function markNode(e) {

  /* If the wheeled node (i.e. e.target) is not the 
  || registered node (i.e. e.currentTarget), then...
  */
  if (e.target !== e.currentTarget) {
    var node = e.target;
    if (node.className === 'A') {
      node.style.outline = '5px dashed blue';
    } else {
      return false;
    }
  }
}
html,
body {
  width: 100%;
  width: 100%
}

fieldset {
  height: 10%;
}

main {
  border: 3px solid lime;
  height: 90%;
  min-height: 250px;
  display: flex;
}

section {
  width: 50%;
  min-height: 250px;
  outline: 3px dashed gold;
  padding: 10px 25px;
}

span {
  height: 50px;
  width: 50px;
  padding: 2px;
  text-align: center;
  font-size: 12px;
  margin: 5px;
  display: inline-block;
}

.A {
  background: rgba(0, 100, 200, .3);
}

.B {
  background: rgba(200, 100, 0, .3);
}

#addB {
  margin-left: 35%
}
<fieldset>
  <legend>addNode</legend>
  <button id='addA'>nodeA</button>
  <button id='addB'>nodeB</button>
</fieldset>
<main>
  <section></section>
  <section></section>
</main>

答案 2 :(得分:0)

您可以非常轻松地使用侦听器动态创建元素。您只需要了解DOM以及如何附加事件侦听器。

下面的示例创建了10个跨度,并为每个跨度附加了一个侦听器。只需将鼠标悬停在跨度上并滚动鼠标滚轮即可。跨度的ID将记录到控制台。

&#13;
&#13;
// Create 10 spans with a scroll listener.
var count = 10;
for (var i = 0; i < count; i++) {
  var span = document.createElement('SPAN');
  span.id = 'foo-bar-' + i;
  span.innerHTML = 'Foo #' + i;
  addEventListener(span, 'mousewheel', performEvent);
  document.body.appendChild(span);
}

// Event function.
function performEvent(e) {
  console.log(e.target.id);
}

// IE 8+ via http://youmightnotneedjquery.com/
function addEventListener(el, eventName, handler) {
  if (el.addEventListener) {
    el.addEventListener(eventName, handler);
  } else {
    el.attachEvent('on' + eventName, function(){
      handler.call(el);
    });
  }
}
&#13;
.as-console-wrapper { max-height: 5em !important; }

span[id^="foo-bar-"] {
  border: thin solid black;
  margin: 0.25em;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

尝试以下方法:

&#13;
&#13;
::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
&#13;
<!DOCTYPE HTML>
<html>
  <body style="overflow: auto;
max-height: 100vh;" onscroll="alert('hi')">
    <div style="height:2000px;width:100%"></div>
  </body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您找到“addEventListener”示例的原因仅仅是因为您需要处理此跨浏览器:

var supportedWheelEvent = "onwheel" in HTMLDivElement.prototype ? "wheel" : document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll";

此外,最好只在一个元素上执行此操作!使用委托事件侦听器来处理所需的所有元素。

HTML示例:

<div id="delegator">
   <div class="handleWheel">handle wheel event here</div>
   <div> no wheel event handled here </div>
   <div class="handleWheel">handle wheel event here</div>
   <div> no wheel event handled here </div>
</div>

JS:

var supportedWheelEvent = "onwheel" in HTMLDivElement.prototype ? "wheel" : document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll";

function handler(e){
    if(e.target.classList.contains('handleWheel')){
        // handle the event here
    }
}

var d = document.getElementById('delegator');
d.addEventListener(supportedWheelEvent, handler);

工作代码集示例: https://codepen.io/Mchaov/pen/zwaMmM