展开和折叠,以锚的链接为目标

Expand and collapse, with a link for an anchor as target

本文关键字:链接 目标 折叠      更新时间:2023-09-26

我正在尝试使用jQuery和jQuery崩溃来建立一个链接选项列表,其中链接可以在第一次单击时展开或折叠,如果它展开,在第二次单击该链接将带您到目的地href.

我开始了一个jsfiddle来解决我的问题:http://jsfiddle.net/smittles/vtuLsh7s/

<div class="expandy" data-collapse>
    <div class="title"><a href="http://google.com">Google!</a></div> 
    <div class="content">
        Lorem ipsum Cupidatat esse tempor reprehenderit ea sint occaecat sint Excepteur commodo esse exercitation.
    </div>
</div>

问题是锚标签得到一个锚标签与jQuery崩溃的href="#"包装。

我怎么能建立一个可折叠的结构像这样,锚标记成为"可链接",如果面板展开?

这个更简单:

javascript代码:

$("#divId").click(function () {
    $('#divId').unbind("click");
    $("#divId").click(function () {
        window.location.replace("http://www.google.com");
    });
});

我稍微改变了一下html:

<div class="expandy" data-collapse>
    <a id='test' href="http://google.com">
      <div class="title">Google!</div> 
    </a>
    <div class="content">
        Lorem ipsum Cupidatat esse tempor reprehenderit ea sint occaecat sint Excepteur commodo esse exercitation.
    </div>
</div>

并添加了这个JS来解决你的问题:

$('#test').click( function() {
    if($(this).hasClass('open'))
    {
       window.location = $(this).attr('href');
    }
});

不需要jQuery的开销。实际上,使用普通javascript很容易做到这一点。

基本上,我们为每个扩展标题中的链接分配一个点击处理程序。

在click处理程序中,我们检查扩展是否打开。

如果不是,我们阻止浏览器重定向,如果是,我们允许用户重定向

无论如何我们都可以切换折叠/展开

不需要任何外部库。

(演示)

(function(){
    "use strict";
    var sections = document.getElementsByClassName('expandy'), section;
    for(var i = 0; section = sections[i]; i++) {
        section.querySelector('.title a').addEventListener('click',function(e) {
            var section = e.target.parentElement.parentElement;
            if(section.style.height == '1em') e.preventDefault();
            section.style.height = section.style.height == '1em' ? 'auto' : '1em';
        },false);
    }
})();