簡體   English   中英

jQuery Border Image(左上,右上,左下,右下)

[英]jQuery Border Image (top-left, top-right, bottom-left, bottom-right)

我正在建立一個網站,當用戶將鼠標懸停在某個產品上時,我想給該圖像添加一個左上,右上,左下和右下的邊框。 由於幾年前不贊成使用CSS屬性border-top-left-image ,因此唯一的解決方案是使用JS。 目前,我的想法是我將span與圖標類一起使用,然后將四個span附加在懸停上,然后將它們從DOM中刪除,這是最好的解決方案,還是有一些更簡單的方法,我不附加四個span和每次將產品懸停時都將其刪除,這是我當前的代碼,告訴我您的想法,任何建議都是對的,謝謝!

CSS

.icon {
    background: url("../images/theme/icons.png");
    overflow: hidden;
    width: 1.6em;
    height: 1.6em;
    position: absolute; 
}


.top-left {
    top: 0; 
    left: 0;
    background-position: -11.2em 24em;
}

.top-right { 
    top: 0;
    right: 0;
    background-position: -1.6em 24em;
}

.bottom-left { 
    bottom: 0;
    left: 0;
    background-position: -8em 24em;
}

.bottom-right { 
    bottom: 0;
    right: 0;
    background-position: -4.8em 24em;
}

HTML

<div class="layout-product">
    <a href="http://www.mysite.com/product/lorem-ipsum-1">
        <div class="product-image">
             <img src="http://www.mysite.com/images/thumbnail/lorem-ipsum-1.jpg" alt="">
        </div>
    </a>
</div>

jQuery的

$('.layout-product').hover(function() { 

    $(this).find('.product-image').append('<span class="icon top-left"></span>'

        + '<span class="icon top-right"></span>'
        + '<span class="icon bottom-left"></span>'
        + '<span class="icon bottom-right"></span>'
    );

}, function() {

    $('.icon').remove();
});

您應該在創建/刪除節點之前嘗試重用它們。 JavaScript與DOM交互所花費的時間越少,並且動畫和UX就會越平滑。 由於您沒有獲取有關懸停事件的任何動態信息,因此您可以將.icon元素放入display: none初始html中。 並且在CSS中或在懸停時使用JS show / hide。 腳本還會阻止頁面加載,因此在一定程度上會影響性能,這顯然取決於腳本的長度。

例如。

(添加到現有的CSS中)

/* Default */
.layout-product .icon {
  display: none;
}

.layout-product:hover .icon {
  display: block; /* or inline-block or whatever you like that isn't none */
}

HTML

<div class="layout-product">
  <a href="http://www.mysite.com/product/lorem-ipsum-1">
    <div class="product-image">
      <img src="http://www.mysite.com/images/thumbnail/lorem-ipsum-1.jpg" alt="">
      <span class="icon top-left"></span>
      <span class="icon top-right"></span>
      <span class="icon bottom-left"></span>
      <span class="icon bottom-right"></span>
    </div>
  </a>
</div>

如果您希望動畫具有更大的靈活性,可以使用Javascript 代替我提供的CSS。

JavaScript的

// I have used a toggle which means it applies for both .mouseenter and .mouseleave 
// which the .hover function alias. If you pass one function rather than two it will
// Use that function for both events. Customize as you like.
$('.layout-product').hover(function(e) { 

  $(this).find('.icon').fadeToggle();

});

同樣不用說,如果您可以避免在html中使用空元素,而可以使用任何css屬性(如您提到的border-image background ,那將是優先選擇的,較少的DOM元素具有更好的性能和可維護性,並且應盡可能避免使用語義上的純粹表示元​​素(表示與內容分離)。

瀏覽器兼容性顯然是一個因素:

暫無
暫無

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

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