A complete guide to CSS style attributes css() and width() in jQuery

A complete guide to CSS style attributes css() and width() in jQuery

1. Basic use of css():

1.1 Get CSS properties

1.1.1 Get a single attribute value (pass in a string)

div {
    width: 100px;
    height: 100px;
    background: red;
}
<div>div1</div>
<script src="./jQuery/jquery-3.6.0.js"></script>
<script>
    console.log( $('div').css('width') );
    console.log( $('div').css('background') );
</script>

Effect: Since background is a composite attribute, getting its value will list all its attributes.

insert image description here

1.1.2 Get multiple attribute values ​​(using arrays)

console.log( $('div').css(['width', 'background']) );

Effect: The obtained multiple attribute values ​​are returned in the form of objects

insert image description here

1.2 Setting CSS properties

1.2.1 Setting a single property value (using a string)

$('div').css('color', 'white');

Effect: The font turns white

insert image description here

1.2.2 Setting multiple property values ​​(using objects)

$('div').css({
    color: 'white',
    width: '200px'
    //You can write '200', '200px', or 200 here, the default unit is pixels});

Effect: The font color is white and the div width becomes 200px

insert image description here

1.2.3 demo: Every time you click on a div, the width increases by 100px

$('div').click(
    $(this).css({
    width: '+=100'}) // Automatically get the current width attribute and add 100px
)

Effect:

insert image description here

2. Basic usage of width() series (same for height() series)

2.1 width()

2.1.1 Get width value

Compared with dom.css('width'), the result of css('width') is a string containing pixel value and unit.
The result of width() is a number, not a string, without units, which is convenient for addition and subtraction.

console.log( $('div').css('width') ); // '100px'
console.log( $('div').width() ); //100 number type

2.1.2 Setting the width value

// console.log( $('div').css('width','200px') );
console.log( $('div').width('200px') );

2.2 innerWidth() and outerWidth()

2.2.1 Value comparison

div {
    width: 100px;
    height: 100px;
    padding: 30px;
    border: 20px solid orange;
    margin: 10px;
    background: red;
}
console.log( $('div').width() ); //100 = content
console.log( $('div').innerWidth() ); //160 = content + padding
console.log( $('div').outerWidth() ); //200 = content + padding + border
console.log( $('div').outerWidth(true) ); //220 = content + padding + border + margin 

insert image description here

2.2.2 Setting value: only changes the width of content

$('div').innerWidth('100'); //Change the total value of content+padding to 100px, padding remains unchanged, and content width becomes 40px
$('div').innerWidth('50'); //padding remains unchanged, content becomes 0
$('div').outerWidth('150');//content+padding+border=content+30*2+20*2=150, content=50
$('div').outerWidth('50');//content+30*2+20*2=50, content=0, padding, margin, border remain unchanged

The box model diagram is as follows: When the set width is smaller than the previous setting, the padding, border, and margin remain unchanged, only the content shrinks until it reaches 0

insert image description here

The width is set larger than the original, and only the content is widened

$('div').innerWidth('300'); 

insert image description here

3.offset() and position()

3.1 Value comparison

offset() takes the position of the element relative to the document; position() takes the position relative to the nearest positioned parent

3.1.1 Parent does not set position

.wrapper {
    width: 300px;
    height: 300px;
    margin: 100px;
    background: #ccc;
}
.content {
    position: absolute;
    left: 150px;
    top: 150px;
    width: 100px;
    height: 100px;
    background: red;
}
<div class="wrapper">
    <div class="content"></div>
</div>
<script src="./jQuery/jquery-3.6.0.js"></script>
<script>
    console.log($('.content').offset());
    console.log($('.content').position());
</script>

Effect: Since the wrapper has no positioning, the closest position to the content is the body, and the position value is relative to the body.
The object returned by offset is originally positioned relative to the document (the default margin of body: 8px is gone due to collapse)

insert image description here

insert image description here

3.1.2 Parent setting position

When the wrapper sets the position:

.wrapper {
    position: relative;
    top: 100px;
    left: 100px;
    width: 300px;
    height: 300px;
    background: #ccc;
}
.content {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: red;
}

Effect:

insert image description here
insert image description here

3.2 Setting value comparison

position() cannot be set manually; offset() can be set manually

$('.content').offset({
    left: 50,
    top: 50
});

Effect: Relative document positioning

insert image description here

4. scrollLeft() and scrollTop()

scrollLeft(): Gets the value of the horizontal scroll bar from the left side
scrollTop(): Gets the value above the vertical scroll bar distance

4.1 Value

.wrapper {
    width: 400px;
    overflow: auto;/*The key to the horizontal and vertical scroll bars*/
}
.content {
    display: inline-block;
    width: 100%;
    height: 100%;
}
$('.content').offset({
    left: 50,
    top: 50
});

Effect:

insert image description here

To get the value on the parent (.wrapper), if the parent is body, you can get the value directly on document: $(document).scrollLeft()

4.2 Setting Values

insert image description here

The vertical scroll bar scrolls upwards. The scroll distance is the distance the text content rushes upwards and the distance the scroll bar is pulled down.

insert image description here
insert image description here

4.3 Small demo

Function: When reading an article, the scroll bar will automatically slide up at regular intervals to display the following content, eliminating the need for manual scrolling

.content {
    width: 400px;
}

The text content is enclosed by a div with a class name of content:

insert image description here

Functional implementation code:

var timer;
var newTop;
timer = setInterval(function () {
    newTop = $(document).scrollTop();
    if (newTop + $(window).height() >= $('body').height()) {
        clearInterval(timer);
    } else {
        console.log('timer');
        $(document).scrollTop(newTop + 20);
    }

}, 100)

The height of the body is extended by the content, so $('body').height() $('.content').height()
When the scroll bar scroll distance + display window height >= actual text height, it means the scroll bar has been pulled to the bottom and the timer can be cleared.

insert image description here

Effect: Keep pulling down, and the timer will be cleared when you reach the bottom.

insert image description here

You will see that there is actually a small piece that does not reach the bottom at the end:

insert image description here

This is because the body has an 8px margin by default, just cancel it

In addition: Try to draw a div to place this automatic scrolling effect to consolidate the understanding of the judgment conditions:

body {
    margin: 0;
}
.wrapper {
    height:400px;
    width: 400px;
    overflow:auto;
}

.content {
    
    display: inline-block;
    width: 100%;
}

The text content is wrapped in a wrapper

var timer;
var newTop;
timer = setInterval(function () {
    newTop = $('.wrapper').scrollTop();
    if (Math.round(newTop + $('.wrapper').height()) >= Math.round($('.content').height())) {
        clearInterval(timer);
        console.log('clear');
    } else {
        console.log('timer');
        $('.wrapper').scrollTop(newTop + 20);
    }

}, 100) 

insert image description here

This concludes this series of articles about the CSS style attributes css() and width() in jQuery. For more information about jQuery’s CSS style attributes, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of CSS custom scroll bar style case
  • Take you to understand the basics of CSS, style
  • Detailed explanation of CSS style penetration problem in Vue
  • BootStrap CSS global style and table style source code analysis
  • CSS page style code
  • How much do you know about the three major styles of CSS?

<<:  Implementation ideas for docker registry image synchronization

>>:  How to configure MySQL master-slave replication under Windows

Recommend

How to use Font Awesome 5 in Vue development projects

Table of contents Install Dependencies Configurat...

How to Use rsync in Linux

Table of contents 1. Introduction 2. Installation...

How to implement the singleton pattern in Javascript

Table of contents Overview Code Implementation Si...

Some notes on mysql create routine permissions

1. If the user has the create routine permission,...

Management of xinetd-based services installed with RPM packages in Linux

Table of contents Preface 1. Startup management b...

CentOS 7.2 builds nginx web server to deploy uniapp project

Panther started as a rookie, and I am still a roo...

Summary of solutions for MySQL not supporting group by

I downloaded and installed the latest version of ...

Key points for writing content of HTML web page META tags

The META tag is an auxiliary tag in the head area...

Implementation ideas for docker registry image synchronization

Intro Previously, our docker images were stored i...

How to handle super large form examples with Vue+ElementUI

Recently, due to business adjustments in the comp...

CocosCreator learning modular script

Cocos Creator modular script Cocos Creator allows...

jQuery implements all shopping cart functions

Table of contents 1. Select All 2. Increase or de...

In-depth understanding of this in JavaScript

In-depth understanding of this in Js JavaScript s...