简体   繁体   English

jQuery-包含文本的嵌套鼠标悬停的onClick <li> 下拉式菜单

[英]jQuery - onClick of nested text-field hover containing <li> dropdown menu

I have 2 username/password text fields inside of <li> . 我在<li>内有2个用户名/密码文本字段。 On :hover of the <li> the drop down appears showing the text fields. <li>:hover上,出现下拉菜单,显示文本字段。 When the user clicks on the text fields, I want the <li> to have the pseudo class :hover so the the fields remain visible if the mouse is moved outside of the contianing <li> . 当用户单击文本字段时,我希望<li>具有伪类:hover因此,如果将鼠标移到包含元素的<li>之外,这些字段将保持可见。

I've tried this code but it doesn't work. 我已经试过了这段代码,但是没有用。

<script>$('#username').on('click',function() {
    $('#li').trigger('hover');});
</script>    

Here is the HTML 这是HTML

<li id="li"><a href="#">Register</a></li>
   <p>Or Login Below</p>
 <form method="post" action="#" name="loginform" id="loginform" class="myClass">
<fieldset>
    <input value="username" type="text" name="username" id="username" onclick="this.value=''" class="left" />
    <input value="password" type="password" name="password" id="password" onclick="this.value=''" class="left" />
    <input type="submit" name="login" id="login2" value="Login" />
</fieldset>
</form>  
</li>

Is the JavaScript wrong or is it possibly conflicting with other JavaScript? JavaScript是错误的,还是可能与其他JavaScript冲突?
Also, would it be easy to make it so 'clicking of the <div> makes the :hover go away, thus hiding the <li> ? 另外,是否容易做到这一点,所以'点击<div>会使:hover消失,从而隐藏<li>吗?

I've tried this code but it doesn't work 我已经尝试过此代码,但无法正常工作

Not sure what is "not working" but I would implement the behavior differently: 不知道什么是“不起作用”,但我会以不同的方式实现该行为:

Triggering 'hover' on click doesn't seem right to me. 在我看来,点击时触发“悬停”似乎不正确。 Code will become fuzzy if the 'hover state' doesn't mean the mouse is hovering of an element. 如果“悬停状态”不表示鼠标悬停某个元素,则代码将变得模糊。

The code will be more readable/logic to just toggle the visibility of the LI on the click event. 该代码将更具可读性/逻辑性,以仅在单击事件上切换LI的可见性。

$('#username').on('click',function() {
    $('#li').toggle();
});

I was going about this wrong. 我正在解决这个错误。 Apparently CSS psuedo-selectors cannot be selected the way I was trying. 显然,不能以我尝试的方式选择CSS伪选择器。
Here is an explanation for anyone else http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover 这是对其他任何人的说明http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover

This ended up working: 最终工作:

<script>$('#username').click(function() {
$('#li').addClass('psuedoClassProperty'); // adds the CSS to display        

}); });

and to hide when clicked off: How do I detect a click outside an element? 并在单击时隐藏: 如何检测元素外部的单击?

<script>
$('html').click(function() {
$('#li').removeClass('psuedoClassProperty');
});
$('#li').click(function(event){
event.stopPropagation();
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM