簡體   English   中英

如何使用jQuery平滑更改項目的背景顏色?

[英]How to change an item's background color smoothly using jquery?

我有一個網頁,對於內部鏈接,我想強調一下訪問者在單擊當前頁面上的內部鏈接后跳轉到的位置。 就像SO的評論或回答通知一樣。 首先,目標的背景將為橙色,然后將其平滑地變回白色。

我本可以這樣做,但是顏色變化並不平滑。

HTML部分

<a href="#section1">go to section 1</a>

<a href="http://google.com">Google</a>

<a name="section1"><a><h3 id="section1">Section 1</h3>

jQuery部分

$(function () {
    $("a[href^='#']").click(
    function () {
        var $id = $(this).attr("href");
        $($id).css({"background-color":"#cc7733", "transition":"background-color"});

        setTimeout(function () {
            $($id).css("background-color", "#ffffff");
        }, 2500);

    });

});

JS小提琴在這里

過渡應該有持續性和寬松性。

{"transition":"background-color 0.5s ease"}

注意: 0.5s是采樣時間,將其更改為您自己的時間。

演示

問題是您要指定"transition":"background-color" ,而不要指定時間范圍。 您需要更改它以包含時間:

..."transition":"background-color 0.2s"

但是,更好的方法是在CSS本身上設置transition屬性,然后使用jQuery為元素提供一個新類:

/* Select any element with a href attribute. */
:link { /* You could use [href], but :link has better browser support */
    transition: 2.5s; /* Transition takes 2.5 seconds. */
}

.changedBackground {
    background: #fff;
}
$($id).addClass('changedBackground');

這樣,您可以將樣式與JavaScript分開,從而允許您僅通過修改CSS即可輕松更改樣式。

您可以像這樣使用.animate()

$($id).stop()
      .css({"background-color":"#cc7733"},1000)
      .animate({"background-color":"#FFF"},1000);

注意:您需要在項目中包括jQuery UI,以使動畫生效。

演示

暫無
暫無

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

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