我有input type="text"
和datalist
,我想在输入框中添加一个固定箭头(svg(,这样当有人点击它时,数据列表就会打开(就像他们点击框一样(
问题是我添加的箭头有默认的cursor-events
,所以默认情况下,当我单击它时,数据列表不会打开
我把cursor-events
改成了none
,问题解决了,但现在的cursor
是text
,我希望鼠标在箭头上时它是pointer
,鼠标在框上时是text
我在这里尝试了解决方案:https://stackoverflow.com/a/25654479/7867670但它对我不起作用
我试图向箭头添加onclick
事件侦听器,并在每次单击箭头时触发input
单击,但也不起作用。
input::-webkit-calendar-picker-indicator {
display: none !important;
}
.wrapper{
position: relative;
display: inline;
left: -25px;
cursor: pointer;
}
.wrapper svg{
pointer-events: none;
}
<input type="text" list="mylist" name="inp" />
<div class="wrapper" onclick="getElementsByName('inp')[0].click();">
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<path fill="currentColor" d="M16.293 9.293L12 13.586L7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z" />
</svg>
</div>
<datalist id="mylist">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</datalist>
据我所知,如果没有JavaScript,这是不可能的。
-
只有当
pointer-events
不是none
时,箭头才能更改cursor
,但input
不会得到点击。 -
input
不能生孩子,所以这也不是一种选择。 -
所有搜索结果都表明,
datalist
无法使用JavaScript或纯html解决方案打开(可靠地?(。
我唯一想到的是以编程方式更改光标:
function isEventInElement(event, element) {
var rect = element.getBoundingClientRect();
var x = event.clientX;
if (x < rect.left || x >= rect.right) return false;
var y = event.clientY;
if (y < rect.top || y >= rect.bottom) return false;
return true;
}
const inputElement = document.querySelector('[name="inp"]')
const inputElementArrow = document.querySelector('.wrapper')
inputElement.addEventListener('mousemove', (evt) => {
if (isEventInElement(evt, inputElementArrow)) {
inputElement.style.cursor = 'pointer'
} else {
inputElement.style.cursor = null;
}
})
input::-webkit-calendar-picker-indicator {
display: none !important;
}
.wrapper {
position: relative;
display: inline;
left: -25px;
pointer-events: none;
}
.wrapper svg {}
<input type="text" list="mylist" name="inp" />
<div class="wrapper" onclick="getElementsByName('inp')[0].click();">
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<path fill="currentColor" d="M16.293 9.293L12 13.586L7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z" />
</svg>
</div>
<datalist id="mylist">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</datalist>
代码形式其他答案:
isEventInElement
:检测元素的客户端区域内是否发生鼠标事件
您希望通过css设置输入的光标。优选地,将css类添加到输入cursor-pointer
并为该选择器创建一些css。
.cursor-pointer {
cursor: pointer !important;
}
如果我没有记错的话,听起来你不希望用户键入输入字段,而是像下拉菜单一样单击它。如果是这样的话,如果可能的话,我建议使用按钮来触发列表。