Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - Seems that onBlur of one element is "overriding" the onclick of another

I have two elements:

<input type="text" name="pmTo" id="pmTo" onkeyup="offerSuggs('none');" onfocus="showSelect();" onblur="hideSelect();" />

and a dynamically created one (this is all part of an auto suggest program):

$suggString .= '<div name="'.$value.'" id="'.$value.'" class="suggMouseOver" onmouseover="highlightDivs(this);" onmouseout="blurDivs(this);" onclick="fillInput(this);">'.$value.'</div>';

Okay, and then there are the event functions that correspond to the onblur of the input element and then the onclick of the div element:

function hideSelect() {
            offerSuggs('checkFinal');
            document.getElementById('nameSugg').style.display="none";
            }


function fillInput(elemName) {
            document.getElementById('pmTo').value=elemName.id;
            }

EDIT: How do I get the onclick to trigger correctly on the element they click on without the onblur event hiding the div first which makes the onclick meaningless? I would still like to retain the functionality of the suggestion div disappearing when the textbox loses focus, however.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are short on answers because your question is confusing. Presumably you have an input that, when focussed, shows a list of suggestions based on the characters entered into the input.

If the user uses the cursor to select an item, then I suppose the blur event of the input fires before the click event of the div and the the div is set to display:none before the click fires, and hence misses the div.

The fix is to call the onblur listener after a short timeout, so:

  <input ... onblur="setTimeout(function(){hideSelect();}, 100);">

Test in a number of browsers, you may need to set the timeout to 200ms or so. It doesn't matter if there's a short, visible delay after the blur event before the suggestions disappear (i.e. a bit too long is better than a bit too short).

Make sure the suggestions don't obscure anything important on the page or users may find them more of a hindrance than a help. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...