【问题标题】:Can I make a div class clickable?我可以让一个 div 类可点击吗?
【发布时间】:2014-04-18 17:08:18
【问题描述】:

我尝试将href 添加到cart-button 类中,如下面的HTML 代码:

    <div class="cart-button" href="#shopping-cart" alt="view-shopping-cart"><span>Shopping Cart (0)</span>
      <div class="cart-dropdown">
        <p class="emptycart">Your shopping cart is empty.</p>
      </div>
    </div>

如您所见,我将href 插入到cart-button 类中,但是当我单击按钮时,页面不会前进到href 页面。

是否可以像上面那样将href 变成div,或者这是错误的?

这是上面 HTML 代码的 CSS:

    .cart-button {
      position: relative;
      left: 700px;
      bottom: 57px;
      width: 180px;
      height:30px;
      cursor: pointer;
      background: url("images/cart-sprite.png") no-repeat 0 0;
    }

    .cart-button:hover { background: url("images/cart-sprite.png") no-repeat 0 -30px; }

    .cart-button span {
      white-space: nowrap;
      position: absolute;
      font-size: 13px;
      font-weight: bold;
      color: #373737;
      padding: 9px 10px 10px 53px;
    }

    .cart-button span:hover { color: #000; }

    .cart-dropdown {
      position: relative;
      top: 30px;
      right: 71px;
      width: 250px;
      height: 100px;
      background: #fff;
      border: 1px solid #ddd;
      display: none;
      opacity: 0;
    }

    .cart-button:hover .cart-dropdown {
      display: block;
      opacity: 1;
    }

    .emptycart {
      position: relative;
      font-size: 11px;
      font-weight: bold;
      padding-top: 8px;
      padding-bottom: 8px;
      color: #fff;
      background: #202020;
      text-align: center;
    }

【问题讨论】:

    标签: css html button href


    【解决方案1】:

    使用&lt;a&gt; 标签。您不能将href 属性添加到任意元素以使其可点击。不是href 使&lt;a&gt; 标签可点击,而是&lt;a&gt; 标签。

    您可以使用 JavaScript 实现类似的功能,但您不应该这样做。使用语义上表示可点击元素的标签 - &lt;a&gt;&lt;button&gt;

    【讨论】:

    • 我明白了,谢谢你让我知道,让我更清楚了。还在学习 HTML 和 CSS :)
    【解决方案2】:

    在 html5 中,您可以将块元素包装在 &lt;a&gt; 标签中。

    http://html5doctor.com/block-level-links-in-html-5/

    所以...

    <a href="#"><div>...</div></a>
    

    【讨论】:

    • 我喜欢你提到这一点,因为以前它是无效的。但是,meagar 的答案更完整-如果这些答案在同一个答案中,我会很高兴;)
    • 哈哈,是的,耻辱。不过还是觉得不对劲。
    【解决方案3】:

    试试

      <a href="https://www.google.co.in/"><div class="cart-button"  alt="view-shopping-cart"></div></a>
    

    DEMO

    【讨论】:

      【解决方案4】:

      如果不使用锚标记,您将无法真正做到这一点。

      但是,您可以将 onClick 事件添加到 div 以触发您想要的任何事件。不过,我个人更喜欢前者。

      【讨论】:

        【解决方案5】:

        如果你愿意,你也可以使用 JQuery,这样你的代码就会看起来像这样:

        $(function () {
             $('.cart-button').click(function() {
                  //GO SOMEWHERE or DO SOMETHING HERE
             });
        });
        

        不要忘记在您的页面中链接 JQuery 库。

        快乐编码...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-06
          • 1970-01-01
          相关资源
          最近更新 更多