如何用jQuery将一个div的宽度增加指定的像素,一旦它被点击

如何用jQuery将一个div的宽度增加指定的像素,一旦它被点击

在这篇文章中,我们将学习如何使用jQuery在点击后将一个分部的宽度增加指定的像素。

我们可以使用JQuery中用于返回和设置元素宽度的width()方法来完成这项任务。因此,当我们点击它时,一个函数被调用,首先我们使用width()方法将div的当前宽度存储在一个变量中,然后增加指定的像素,并使用JQuery的width(value)方法设置其宽度。

语法:

// To return the width of the selected element
(selector).width()

// To set the width of the selected element(selector).width(value)

示例:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <script src=
"https://code.jquery.com/jquery-3.5.0.js">
    </script>
 
    <style>
        body {
            color: green;
            font-size: 30px;
        }
 
        div {
            font-size: 40px;
            background-color: rgb(190, 190, 190);
            width: 300px;
            border: solid 4px red;
        }
 
        button {
            font-size: 30px;
        }
    </style>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <div onclick="fun()">
            Click to Div to increase the width
        </div>
    </center>
 
    <script>
         
        // Width of the div 点击前ing button
        var w = ("div").width();
 
        // Increment that we want to do
        var inc = 200;
        function fun() {
 
            // Increase width by 200 and set
            ("div").width(w + inc);
        }
    </script>
</body>
 
</html>

输出:

如何用jQuery将一个div的宽度增加指定的像素,一旦它被点击?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

jQuery 方法