防止组合框和镶边的默认行为
我正在尝试这样做,当单击组合框时,应该打开列表,但应该弹出一个警报。
我有这样的代码:
$('select').focus(function() {
this.blur();
window.focus();
});
$('select').click(function(){
alert('Clicked but did not open');
});
这在 FF 中工作正常,但在 chrome 中不起作用,
知道为什么吗?
先感谢您...
I am trying to do, that when clicking on a combobox, the list should open, but instead a alert should pop up.
I have this code:
$('select').focus(function() {
this.blur();
window.focus();
});
$('select').click(function(){
alert('Clicked but did not open');
});
This works fine in FF, but doesnt work in chrome,
Any idea why?
Thank you in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了防止事件冒泡,您应该使用
preventDefault()
以实现跨浏览器兼容性。To prevent the event from bubbling up you should use
preventDefault()
for cross-browser compatibility.可以正常
在 Chrome、IE 9(不是 8)和 Opera(至少版本 11.61,这是我安装的版本)中 工作。它在 Firefox 中不起作用,不知道为什么。然而,元素上的模糊和窗口上的焦点对我来说永远不起作用,无论是在鼠标按下还是单击时。
受到这里被否决两次的答案的启发(http://stackoverflow.com/questions/1905464/html-select-dropdown),我想出了这个小小的变化(原来的使整个窗口闪烁,有点丑陋) :
现在,对于 FF(我有版本 10)和 IE < 9,这意味着轻微的闪烁,因为下拉列表实际上打开后立即关闭,但 PreventDefault 可以使其在所有其他现代浏览器中正常工作。 Select 是邪恶的,我认为没有一个好的跨浏览器方法来控制下拉列表是否显示。根据互联网上的谣言, return false 应该做一些事情,所以我把它留在那里,可能它在旧浏览器中确实有效。
PS:在你的问题中,你的意思是“[...]列表应该不打开,而是[...]”,对吗?
Doing
works in Chrome, IE 9 (not 8), and Opera (at least version 11.61, which is the one I have installed). It doesn't work in Firefox, don't know why. However, the blur on the element and the focus on the window don't work for me ever, neither in mousedown nor on click.
Inspired by an answer that got downvoted twice here (http://stackoverflow.com/questions/1905464/html-select-dropdown), I came up with this little variation (the original makes the whole window flicker, it's a tad hideous):
Now, for FF (I have version 10) and IE < 9, this means a slight flicker, as the dropdown actually opens to close right after, but preventDefault is there to make it work well in every other modern browser. Select is evil, I don't think there's a good cross-browser way to control whether the dropdown shows or not. Return false should do something according to the rumors on the Internet, so I left it there, may be it does work in older browsers.
P.S.: In your question you meant "[...] the list should not open, but instead [...]", right?
Demo
添加返回 false 作品
Demo
Adding return false works