Focus button from javascript withour clicking it

最后都变了- 提交于 2019-12-24 10:59:34

问题


I call

element.focus();

Where element is HTMLInputElement of type=button. But then the browser clicks the button! That's in mozilla and chrome.

How do i highlight the button with selection, but not initiate the click event?


回答1:


No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit

It does exactly what you want it to.




回答2:


Well, i've identified the reason. I was handling the onkeydown event for Enter key. The solution is to use e.preventDefault();

function ConvertEnterToTab(s, e, numSkipElements) {
            var keyCode = e.keyCode || e.htmlEvent.keyCode;
            if (keyCode === 13) {
                var tabIndex = s.tabIndex || s.inputElement.tabIndex;
                if (numSkipElements == undefined) {
                    numSkipElements = 0;
                }

                var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
                if (nextElement != undefined) {
                    nextElement.focus();
                    return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
                }
            }
        }

        function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
            if (maxTabIndex == undefined) {
                maxTabIndex = 100;
            }

            var tempIndex = currentTabIndex + 1;
            while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
                tempIndex++;
            }

            return $('[tabindex=' + tempIndex + ']')[0];
        }


来源:https://stackoverflow.com/questions/12584830/focus-button-from-javascript-withour-clicking-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!