HTML - DOM Style 物件 scrollBehavior 屬性



HTML DOM Style 物件的**scrollBehavior**屬性指定平滑滾動效果,而不是在使用者點選可滾動框內的連結時立即滾動。

語法

設定 scrollBehavior 屬性
object.style.scrollBehavior= "auto | smooth | initial | inherit";
獲取 scrollBehavior 屬性
object.style.scrollBehavior;

屬性值

描述
auto 這是預設值,滾動框在元素之間立即滾動。
smooth 它指定元素之間平滑滾動效果。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回所選元素的 scrollBehavior 屬性的當前值。

HTML DOM Style 物件“scrollBehavior”屬性示例

以下示例使用列表和 div 元素解釋 scrollBehavior 屬性以滾動瀏覽不同的部分。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object right Property
    </title>
    <style>
        div {
            height: 700px;
            border: 2px solid #04af2f;
            }
        #section1 {
            background-color: rgb(202, 249, 249);
        }
        #section2 {
            background-color: rgb(241, 189, 238);
        }
        #section3 {
            background-color: rgb(248, 222, 161);
        }
    </style>
</head>
<body>
    <h3>
        Click on the links in list or links inside 
        three section before and after clicking on 
        'Change scoll Behavior' button to see change 
        in scroll effects using smooth scroll behavior
        property.
    </h3>
    <button onclick="fun()">Change scoll Behavior</button>    
    <br><br>
    <ul>
        <li>
            <a href="#section3">Jump to section 3</a>
        </li>
        <li>
            <a href="#section2">Jump to section 2</a>
        </li>
        <li>
            <a href="#section1">Jump to section 1</a>
        </li>
    </ul>
    <div id="section1">
        This is Section 1 
        <br>
        <a href="#section2">Jump to section 2</a>
        <br>
        <a href="#section3">Jump to section 3</a>
    </div>
    <div id="section2">
        This is Section 2
        <br>
        <a href="#section3">Jump to section 3</a>
        <br>
        <a href="#section1">Jump to section 1</a>
    </div>
    <div id="section3">
        This is Section 3
        <br>
        <a href="#section1">Jump to section 1</a>
        <br>
        <a href="#section2">Jump to section 2</a>
    </div>
    <script>
        function fun() {
            document.documentElement.style
                .scrollBehavior = "smooth";
        }   
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
scrollBehavior 是 61 是 79 是 36 是 15.4 是 48
html_dom_style_object_reference.htm
廣告