Javascript 将链接 <a> 包裹在 <div> 周围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5320404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:39:24  来源:igfitidea点击:

Wrap link <a> around <div>

javascripthtml

提问by BobScon

Is it possible to wrap an <a>tag around <div>s like so:

是否可以像这样<a><div>s周围包裹一个标签:

<a href=etc etc>
    <div class="layout">
        <div class="title">
        Video Type
            <div class="description">Video description</div>
        </div>
    </div>
</a>

Eclipse is telling me the div's are in the wrong place? If this is not allowed. How can I make the entire 'layout' class become a link?

Eclipse 告诉我 div 的位置不对?如果这是不允许的。我怎样才能让整个“布局”类成为一个链接?

回答by Yi Jiang

That structure would be valid in HTML5 since in HTML5 anchors can wrap almost any element except for other anchors and form controls. Most browsers nowadays have support for this and will parse the code in the question as valid HTML. The answer below was written in 2011, and may be useful if you're supporting legacy browsers (*cough* Internet Explorer *cough*).

这种结构在 HTML5 中是有效的,因为在 HTML5 中,锚可以包装除其他锚和表单控件之外的几乎所有元素。现在大多数浏览器都支持这一点,并将问题中的代码解析为有效的 HTML。下面的答案写于 2011 年,如果您支持旧版浏览器(*咳嗽* Internet Explorer *咳嗽*),则可能会有用。



Older browsers without HTML5 parsers (like, say, Firefox 3.6) will still get confused over that, and possibly mess up the DOM structure.

没有 HTML5 解析器的旧浏览器(比如 Firefox 3.6)仍然会对此感到困惑,并可能弄乱 DOM 结构。

Three options for HTML4 - use all inline elements:

HTML4 的三个选项 - 使用所有内联元素:

<a href=etc etc>
    <span class="layout">
        <span class="title">
        Video Type
            <span class="description">Video description</span>
        </span>
    </span>
</a>

Then style with display: block

然后风格与 display: block



Use JavaScript and :hover:

使用 JavaScript 和:hover

<div class="layout">
    <div class="title">
    Video Type
        <div class="description">Video description</div>
    </div>
</div>

And (assuming jQuery)

和(假设 jQuery)

$('.layout').click(function(){
    // Do something
}):

And

.layout:hover {
    // Hover effect
}


Or lastly use absolute positioning to place an aanchor with CSS to cover the whole of .layout

或者最后使用绝对定位来放置一个a带有 CSS的锚点来覆盖整个.layout

<div class="layout">
    <div class="title">
    Video Type
        <div class="description">Video description</div>
    </div>
    <a class="more_link" href="somewhere">More information</a>
</div>

And CSS:

和 CSS:

.layout {
    position: relative;
}

.layout .more_link {
    position: absolute;
    display: block;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    text-indent: -9999px;
    z-index: 1000;
}

This won't work with older versions of IE, of course.

当然,这不适用于旧版本的 IE。

回答by Kristian Seedorff

While the <a>tag is not allowed to contain <div>element, it is allowed to contain other inline elements such as <span>.

虽然<a>标签不允许包含<div>元素,但允许包含其他内联元素,例如<span>.

When I encountered the problem i swapped the div tag with a <span>. Since the span tag is an inline element, you need to apply a display:blockto the css of your <span>element, in order to make it behave like the <div>block element. This should be valid xhtml and does not require any javascript.

当我遇到问题时,我将 div 标签换成了<span>. 由于 span 标签是一个内联元素,您需要将 adisplay:block应用于<span>元素的 css,以使其表现得像<div>块元素。这应该是有效的 xhtml 并且不需要任何 javascript。

Here's an example:

下面是一个例子:

<a href="#">
    <span style="display:block">
        Some content. Maybe some other span elements, or images.
    </span>
</a>

回答by photowalkthrough

Another simple solution - just add an onclick event handler to the div thusly:

另一个简单的解决方案 - 只需向 div 添加一个 onclick 事件处理程序:

<div class="layout" onclick="location.href='somewhere'">
    <div class="title">
    Video Type
        <div class="description">Video description</div>
    </div>
</div>

This works great for me but there is one small gotcha. I'm not sure how search engine friendly this is. I fear that google's web crawlers might not find this link so I also tend to include a traditional A HREF link somewhere in the block like this:

这对我很有用,但有一个小问题。我不确定这对搜索引擎有多友好。我担心谷歌的网络爬虫可能找不到这个链接,所以我也倾向于在块的某个地方包含一个传统的 A HREF 链接,如下所示:

<div class="layout" onclick="location.href='destination_url'">
    <div class="title">
    Video Type
        <div class="description">Video description</div>
    </div>
    <a href="destination_url">This is a link</a>
</div>

回答by Eddie B

Timothy's solution is correct ... instead of wrapping an anchor around a div ... you simply give layout to the anchor element with display:block and add the size and width of the anchor ...

Timothy 的解决方案是正确的......而不是在 div 周围包裹一个锚......你只需使用 display:block 为锚元素提供布局并添加锚的大小和宽度......

.div_class   { width: 100px; height: 100px; }
.div_class a { width: 100px; height: 100px; display: block; }

<div class='div_class'><a href="#"></a></div> 

回答by Kushal Jayswal

I had tried to create custom solution using jQuery, which would imitate same behavior as atag does, for parent DIV.

我曾尝试使用 jQuery创建自定义解决方案,它会a为父 DIV模仿与标记相同的行为。

DEMO:https://jsfiddle.net/kutec/m9vxhcke/

演示:https : //jsfiddle.net/kutec/m9vxhcke/

As per W3C standard, you cannot do this:

根据 W3C 标准,您不能这样做:

<div class="boxes">
    <a href="http://link1.com" target="_blank">
        <div class="box">
            <h3>Link with _blank attr</h3>
        </div>
    </a>
</div>

You must follow this:

你必须遵循这一点:

<div class="boxes">
    <div class="box">
        <h3>
            <a href="http://link1.com" target="_blank">Link with _blank attr</a>
        </h3>
    </div>
</div>

But by following above code, you wouldn't get the whole DIV clickable :).

但是按照上面的代码,你不会得到整个 DIV 可点击:)。

Correct structure should be something like this, which also allows you to click over the DIV to redirect on the given hrefvalue:

正确的结构应该是这样的,它也允许你点击 DIV 以重定向给定的href

<div class="boxes" data-href="http://link1.com" data-target="_blank">
    <div class="box">
        <h3>
            <a href="http://link1.com" target="_blank">Link with _blank attr</a>
        </h3>
    </div>
</div>

Simple Solution:

简单的解决方案

$(function() {  
    $('.boxes a').each(function(){
        var aTag = $(this).attr('href');

        $(this).parent().attr('data-href',aTag);        

        $("[data-href]").click(function() {
            window.location.href = $(this).attr("data-href");
            return false;
        });
    })  
}(jQuery));

Dynamic Solution:

动态解决方案

(function ( $ ) { 
    $.fn.dataURL = function() {

        // variables
        var el = $(this);
        var aTag = el.find('a');
        var aHref;
        var aTarget;

        // get & set attributes
        aTag.each(function() {
            var aHref = $(this).attr('href');
            $(this).parent().attr('data-href',this);

            aTarget = $(this).attr('target');
            $(this).parent().attr('data-target',aTarget);
        });

        // imitation - default attributes' behavior on "data-" attributes
        $(el).delegate('[data-href]','click', function() {
            var loc = window.location.href;
            loc = $(this).attr("data-href");
            aTarget = $(this).attr('data-target');

            if(aTarget == "_blank"){
                window.open(loc);
            } else {
                window.location = loc;
            }

            return false;
        });     

        //removing attributes from selector itself
        el.removeAttr('data-href');
        el.removeAttr('data-target');

        // css
        $('[data-href]').css('cursor','pointer');
    };
}( jQuery ));

Final call:

最后电话

<script>
    $('.boxes').dataURL();
</script>

Hope this would be helpful :)

希望这会有所帮助:)

回答by Timothy Khouri

You would just want to style the "a" tag as display: block;

您只想将“a”标签的样式设置为 display: block;

Eclipse is appropriately telling you that your HTML is not to spec (as a div tag is not allowed in an anchor tag).

Eclipse 恰当地告诉您,您的 HTML 不符合规范(因为锚标记中不允许使用 div 标记)。

But, since you seem to want to be visuallymaking the anchor look like a big-ol-box, then simply style it as such :)

但是,由于您似乎希望在视觉上使锚点看起来像一个大的 ol-box,那么只需将其设置为这样 :)