简体   繁体   English

正在联系一个 <div> 使用javascript可以接受吗?

[英]Is linking a <div> using javascript acceptable?

I want to link an entire <div> , but CSS2 does not support adding an href to a div (or span for that matter). 我想链接整个<div> ,但CSS2不支持将div添加到div(或者跨度)。 My solution is to use the onClick property to add a link. 我的解决方案是使用onClick属性添加链接。 Is this acceptable for modern browsers? 这对现代浏览器来说是否可接受

Example code: 示例代码:

<div class="frommage_box" id="about_frommage" onclick="location.href='#';">
            <div class="frommage_textbox" id="ft_1"><p>who is Hawk Design?</p></div>

My test page is at http://www.designbyhawk.com/pixel . 我的测试页面是http://www.designbyhawk.com/pixel Updated daily. 每日更新。

Thanks for the help. 谢谢您的帮助。

You don't need to do that. 你不需要这样做。 There's a perfectly simple and standards-compliant way to do this. 这是一种完全简单且符合标准的方法。

Block-level elements will by default take up the entire available width. 默认情况下,块级元素将占用整个可用宽度。 a elements are not by default block-level, but you can make them so with display: block in CSS. a元素不是默认的块级别,但你可以用CSS中的display: block来实现它们。

See this example (no Javascript!). 看到这个例子 (没有Javascript!)。 You can click anywhere in the div to access the link, even though the link text doesn't take up the whole width. 您可以单击div中的任意位置来访问该链接,即使链接文本不占用整个宽度。 You just need to remove that p element and make it an a . 您只需删除该p元素并使其成为a

Attaching a click event handler to a <div> element will work for your users with JavaScript enabled. 将click事件处理程序附加到<div>元素将适用于启用了JavaScript的用户。

If you're looking for a progressive enhancement solution, however, you'll want to stick with a <a> element. 但是,如果您正在寻找渐进增强解决方案,那么您需要坚持使用<a>元素。

It is acceptable, only it's not good for SEO. 这是可以接受的,只有它对SEO不好。

Maybe you can make a <a> element act like a div? 也许你可以让<a>元素像div一样? (settings it's style to display:block etc.) (设置显示的样式:块等)

It will work in every browser(even IE6). 它适用于每个浏览器(甚至是IE6)。 The only problem with this is that search engines probably won't fetch it since it's javascript. 唯一的问题是搜索引擎可能无法获取它,因为它是javascript。 I see no other way to be able to make an entire div click-able though. 我认为没有其他方法可以使整个div可点击。 Putting an "a" tag around it won't work in all browsers. 在其周围添加“a”标记不适用于所有浏览器。

HTML: HTML:

<div class='frommage_box'>
    <a href='location.html'>CONTENT GOES HERE</a>
</div>

CSS: CSS:

.frommage_box a{
    display:block;
    height:100%;
}

By default block elements take up 100% width. 默认情况下,块元素占用100%的宽度。 We adjust the height to 100%. 我们将高度调整为100%。 And this will allow spiders to crawl yoru page. 这将允许蜘蛛爬行yoru页面。

If all you're trying to achieve is a large clickable box, try setting the following CSS on an anchor: 如果你想要实现的只是一个大的可点击框,请尝试在锚点上设置以下CSS:

a {
   display: block;
   padding: 10px;
   width: 200px;
   height: 50px;
}

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

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