Checkbox style

Trở về

  • 3,458

Một lúc nào đó bạn cần những button đối ứng như một checkbox, thì đoạn code sau đây sẽ giúp bạn.

Xử lý thành phần tương tự input checkbox

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Học Web Chuẩn</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('p').click(function(){
        $(this).toggleClass('checked');
    });
});
</script>
<style>
* { /* reset lại margin và padding cho các tag */
    margin: 0;
    padding: 0;
}
p {
    border: 1px solid blue;
    cursor: pointer;
    padding: 8px;
    text-align: center;
    width: 80px;
}

.checked { background: #dcfcfb; }
</style>
</head>
<body>
<p>checkbox</p>
</body>
</html>

Hiển thị trình duyệt:

Cách sử dụng trên tương tự như cách sử dụng checkbox sau đây, tuy nhiên chưa thể lấy dữ liêu như checkbox được.

So sánh code HTML trước và sau khi có jQuery:

Trước khi có jQuery Sau khi có jQuery

<p>checkbox</p>

<p class="checked">checkbox</p>

Download file để thực hành

Xử lý cho một danh sách

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Học Web Chuẩn</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('ul').delegate('li','click',function(){
        $(this).toggleClass('checked');
    });
});
</script>
<style>
* { /* reset lại margin và padding cho các tag */
    margin: 0;
    padding: 0;
}
li {
    border: 1px solid blue;
    cursor: pointer;
    float: left;
    list-style: none;
    margin-right: 5px;
    text-align: center;
    line-height: 30px;
    height: 30px;
    width: 30px;
}

.checked { background: #fff000; }
</style>
</head>
<body>
<ul>
<li>01</li>
<li>02</li>
<li>03</li>
<li>04</li>
<li>05</li>
</ul>
</body>
</html>

Hiển thị trình duyệt:

Cách sử dụng trên tương tự như cách sử dụng checkbox sau đây:

So sánh code HTML trước và sau khi có jQuery:

Trước khi có jQuery Sau khi có jQuery

<ul>
<li>01</li>
<li>02</li>
<li>03</li>
<li>04</li>
<li>05</li>
</ul>

<ul>
<li>01</li>
<li class="checked">02</li>
<li>03</li>
<li>04</li>
<li>05</li>
</ul>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.