指针事件:无,但捕获点击

新手上路,请多包涵

是否可以只允许单击并禁用所有其他指针事件

顶层有一个搜索栏

底层有词云

我在顶层设置了 pointer-events:none ,所以词云中的所有词即使在搜索栏下方也可以悬停。

但我希望启用输入文本上的点击事件,以便当用户想要输入内容时,他可以。

在此处输入图像描述

这是一个相关的小提琴

文本在输入后面,但它应该可以悬停,输入在文本上方,但它应该可以使用鼠标聚焦,以允许用户输入。

注意:它看起来像一个占位符的东西,但它不是。请查看原始图片以了解我想要实现的目标。

原文由 gaurav5430 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 247
1 个回答

我认为这应该有效。监听父容器上的点击事件,获取 event.clientXevent.clientY 值以检查它们是否在 input 的范围内如果是这样,您可以将焦点设置到 input 元素。您仍然可以确定是否单击了 input 元素下方的随机词之一。

 var d = document,
    c = d.getElementsByClassName('container').item(0),
    inp = d.createElement('input'),
    a = 50,
    i = 0;

/*
 | get the clientBoundingRect of the input element
 | and if the mouse x and mouse y positions are within
 | the bounds set the focus on to the input element.
------------------------------------------------------------- */
function inpClickHndl (evt) {
  var inpRect = inp.getBoundingClientRect(),
      x = evt.clientX,
      y = evt.clientY,
      l = inpRect.left,
      w = l + inpRect.width,
      t = inpRect.top,
      h = t + inpRect.height;

  if (x >= l && x <= w && y >= t && y <= h) {
    inp.focus();
  }
}

/*
 | ignore this, it's just to create the random words.
------------------------------------------------------------- */
function wordClickHndl (evt) {
  this.style.color = "yellow";
}

for (i; i < a; i++) {
  var p = d.createElement('p'),
      t = d.createTextNode('Random Word');
  p.appendChild(t);
  p.addEventListener('click', wordClickHndl, false);
  p.style.position = 'absolute';
  p.style.top = Math.floor(Math.random() * (window.innerHeight - 80)) + -40 + 'px';
  p.style.left = Math.floor(Math.random() * (window.innerWidth - 80)) + -40 + 'px';
  p.style.fontSize = Math.floor(Math.random() * (38 - 8)) + 8 + 'px';
  p.style.fontWeight = 'bold';
  c.appendChild(p);
}

inp.setAttribute('type', 'text');
c.appendChild(inp);

/*------------------------------------------------------------- */

// add a click handler to your parent element.
c.addEventListener('click', inpClickHndl, false);
 body {
  margin: 0;
  font-family: sans-serif;
}

.container {
  position: relative;
  height: 100vh; width: 100vw;
  background-color: #1a1a1a;
}

.container p {
  color: green;
}

.container p:hover {
  color: red;
  cursor: pointer;
}

.container input {
  position: absolute;
  top: 50%; left: calc(50% - 85px);
  pointer-events:none;
  opacity: .75;
}
 <div class="container"></div>

原文由 DavidDomain 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏