thực hành - hiển thị password

Trong bài thực hành này, chúng ta sẽ tìm hiểu cách hiển thị password bằng HTML, CSS và JavaScript.

Hiển thị password


Xem kết quả

Cách tạo hiển thị password


Bước 1) Thêm HTML:

Ví dụ

<div class="containerx">
    <label for="pw" class="label">Password</label>
    <input type="password" id="pw" value="Your Password" />
    <label class="checkBox">Show Password
        <input type="checkbox" id="checkbox" />
        <span class="check"></span>
    </label>
</div>

Bước 2) Thêm CSS:

Ví dụ

/* Tạo kiểu cho phần tử label */
.containerx > .label {
    display:inline-block;
    margin-bottom:5px;    
}
/* Tạo kiểu cho phần tử input */
.containerx > input {
    border:none;
    background-color:#f1f1f1;
    padding:10px;
    width:170px;
    display:block;
    margin-bottom:20px;    
    border-radius:5px;
}
/* Thêm hiệu ứng khi lấy nét */
.containerx > input:focus {
    outline:none;
    box-shadow:0 0 3px dodgerblue;
    transition:box-shadow 0.2s;    
}
/* Tạo kiểu vùng chứa checkbox */
.checkBox {
    position:relative;
    display:inline-block;    
    padding-left:30px;
    cursor:pointer;
    user-select:none;
}
/* Ẩn phần tử input */
.checkBox > input {
    width:0;
    height:0;
    opacity:0;    
}
/* Tạo kiểu cho lớp checkbox */
.checkBox > .check {
    display:inline-block;
    width:24px;
    height:24px;
    background-color:#ccc;
    position:absolute;
    top:-4px;
    left:0;
    border-radius:3px;
}
/* Thay đổi màu nền khi hộp checkbox được checked */
.checkBox > input:checked + .check {
    background-color:dodgerblue;    
}
/* Tạo kiểu cho dấu tick check và ẩn mặc định */
.checkBox > .check:after {
    content:"";
    position:absolute;
    top:1px;
    left:8px;
    width:3px;
    height:10px;
    border:3px solid;
    border-color:transparent white white transparent;
    transform:rotate(45deg);
    display:none;    
}
/* Hiển thị dấu tick khi hộp checkbox được checked */
.checkBox > input:checked + .check:after {
    display:inline-block;    
}

Bước 3) Thêm JavaScript:

Ví dụ

<script>

// Khai báo các biến và lấy giá trị
var pw, checkBox;
pw = document.getElementById('pw');
checkBox = document.getElementsByClassName('checkBox')[0];

// Gán sự kiện onclick thay đổi thuộc tính phần tử input
checkBox.onclick = function() {
    if(checkbox.checked == true) {
        pw.type = "text";
    }else{
        pw.type = "password";
    }    
}
</script>

Xem kết quả