簡體   English   中英

單擊下拉菜單中的鏈接不起作用

[英]Clicking on link inside dropdown menu doesn't work

我有一個dropdown菜單工作正常,但當我在dropdown菜單中添加一個鏈接時,該鏈接不起作用。

檢查這里的小提琴,然后嘗試點擊link2和google鏈接; 這是google鏈接不起作用。

HTML

<div class="menu">
    <div class="link">
        <a href="#">Link 1</a>
        <div class="dropdown">
            Content for dropdown 1
        </div>
    </div>
    <div class="link">
        <a href="#">Link 2</a>
        <div class="dropdown">
            <a href="http://google.com">Google</a>
        </div>
    </div>
</div>

JQUERY

$('.link a').on("click", function(e){
    e.preventDefault();
    $(this).parent('.link').siblings().children('.dropdown').fadeOut();
    $(this).siblings('.dropdown').fadeToggle();
});

 $(document).mouseup(function (e)
{
var container = $(".dropdown");

if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
{
    container.hide();
}
});

CSS

    .link {
    display: inline-block;
    position: relative;
    float: right;
}

.link a {
    padding: 10px;
}

.link .dropdown {
    display: none;
    position: absolute;
    top: 20px;
    right: 0px;
    color: white;
    background: #999;
    height: 200px;
    width: 200px;
    padding: 20px;
    border: 1px solid red;
}

http://jsfiddle.net/abLku7e1/2

不知道怎么解決這個問題?
提前致謝

e.preventDefault(); 的問題,這是對.link a所有 a的decendents .link 使用.link > a作為父級鏈接。

>指直接孩子。

嘗試這個:

$('.link > a').on("click", function(e){
    e.preventDefault();
    $(this).parent('.link').siblings().children('.dropdown').fadeOut();
    $(this).siblings('.dropdown').fadeToggle();
});

您只想定位.link的直接后代。

我有一個非常相似的問題。 我的CSS菜單有:

<ul>
  <li><a href="#internal link"> Working </a></li>
  <li><a href="http://external link"> Not working </a></li>
</ul>

和你一樣,我的javascript使用了e.preventDefault(); 單擊后關閉菜單,對於外部鏈接,它將關閉菜單而不實際轉到該外部鏈接。

我通過添加跨度來解決它:

<ul>
  <li><a href="#internal link"> Working </a></li>
  <li> <span> <a href="http://external link"> </span> Now its working </a></li>
</ul>

將JS代碼更改為僅作用於第一個鏈接而不是所有子鏈接(如下所示)

    $('.link>a').on("click", function(e){
    e.preventDefault();
    $(this).parent('.link').siblings().children('.dropdown').fadeOut();
    $(this).siblings('.dropdown').fadeToggle();
});

$(document).mouseup(function (e)
{
    var container = $(".dropdown");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

注意鏈接>平均只有第一級

http://jsfiddle.net/neka5u0d/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM