Effects encountered in JS web page development

JS common special effects JD show...
JD show hidden password
Taobao close QR code
Eye icon to show or hide the contents of the input text box
Imitation Sina registration password box
Jingdong countdown
Send a text message. You can't click again within 5 seconds
Click the pop-up dialog box to drag
Moving end drag element
Local storage - remember user name
Rotation chart
JS verification code

JS common special effects

JD show hidden password

Put a label in the box and a picture in it, using absolute positioning. Put another input box. The default type is password. To achieve the effect, click the eye and the input content will be displayed as a text box. Therefore, click here to listen for click events

<div> <label for=""> <img src="images/close.png" alt="" id="eye"> </label> <input type="password" value="" id="pas"> </div> <script> var eye = document.getElementById('eye'); var pas = document.getElementById('pas'); var flag = 0; eye.onclick = function () { if (flag == 0) { pas.type = 'text'; eye.src='images/open.png'; flag=1; }else{ pas.type='password'; eye.src = 'images/close.png'; flag=0; } } </script>

Taobao close QR code

A picture is placed in the box, and an i tag is closed. It is absolutely positioned in the upper left corner of the picture. JS obtains btn. Box monitors btn click events and sets the display of box

<style> .box { position: relative; width: 78px; height: 88px; margin: 100px auto; border: 1px solid #ccc; text-align: center; font-size: 12px; color:#f40; } .box img { width: 60px; margin-top: 5px; } .close-btn { position: absolute; top: -1px; left: -17px; width: 14px; height: 14px; border: 1px solid #ccc; line-height: 14px; /* The mouse turns into a finger */ cursor: pointer; } </style> </head> <body> <div> Taobao QR code <img src="images/tao.png" alt=""> <i>x</i> </div> <script> // 1. Use element.style to modify the element style, which is suitable for less styles or simple functions var btn=document.querySelector('.close-btn'); var box=document.querySelector('.box'); btn.onclick=function(){ box.style.display='none'; } </script>

Eye icon to show or hide the contents of the input text box

The default type of text box is type, and the default value is mobile phone
Use JS to get the input box and listen for the events of getting the focus and losing the focus of the input box

<input type="text" value="mobile phone"> <script> var text=document.querySelector('input'); text.onfocus=function(){ // Get focus if(this.value==='mobile phone'){ this.value=''; } this.style.color='#333'; } text.onblur=function(){ if(this.value===''){ this.value='mobile phone'; } this.style.color='#999'; } </script>

effect

Imitation Sina registration password box

There is an input with the type of password in the box, and the p tag is used to prompt you to enter
JS gets input, and MES listens for the event that the input box loses focus. When ipt.value.length does not meet the input requirements, change the style and text of the prompt text

<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .register { width: 600px; margin: 100px auto; } .message { display: inline-block; color: #999; background: url(images/mess.png) no-repeat left center; padding-left: 20px; } .red { color: red; background-image: url(images/wrong.png); } .green { color: green; background-image: url(images/right.png); } </style> </head> <body> <div> <input type="password"> <p>Please enter 6~16 Bit password</p> </div> <script> var ipt = document.querySelector('.ipt'); var mess = document.querySelector('.message'); ipt.onblur = function () { // Judge ipt.value.length length value when losing focus if (this.value.length < 6 || this.value.length > 16) { mess.className = 'message red'; mess.innerHTML = 'Input error, please re-enter!' } else { mess.className = 'message green'; mess.innerHTML = 'The password format is correct'; } } </script> </body>

Jingdong countdown

Obtain the hours, minutes and seconds, and perform format conversion while starting the timer. If it is less than 10, fill in zero

<div> <span></span> <span></span> <span></span> </div> <script> // Get hours, minutes and seconds var hour = document.querySelector('.hour'); var minute = document.querySelector('.minute'); var second = document.querySelector('.second'); var inputTime = new Date('2021-9-24 22:00:00'); countDown(); // Turn on the timer setInterval(countDown,1000); function countDown() { var currentTime = new Date(); var times = (inputTime - currentTime) / 1000; var h = parseInt(times / 60 / 60 % 24); h = h < 10 ? '0' + h : h; hour.innerHTML = h; var m = parseInt(times / 60 % 60); m = m < 10 ? '0' + m : m; minute.innerHTML = m; var s = parseInt(times % 60); // Current seconds s = s < 10 ? '0' + s : s; second.innerHTML = s; } </script>

Send a text message. You can't click again within 5 seconds

After clicking the button, it cannot be clicked within 5 seconds
Listen for the click event of the button. Disabled is disabled after the button is clicked. Since the contents of the button change, a timer is required. You can define a variable. If the variable changes to 0, stop the timer and press the reset button

<body> cell-phone number:<input type="text"><button>send out</button> <script> // After clicking the button, the button cannot be clicked again within 5 seconds to prevent repeated sending var button = document.querySelector('button'); var time = 5; button.addEventListener('click', function () { this.disabled = true; timer=setInterval(function () { if (time == 0) { //Clear timer and seconds clearInterval(timer); button.disabled = false; button.innerHTML = 'send out'; time = 5; } else { button.innerHTML = 'also' + time + 'second' time--; } }, 1000) }) </script>

Click the pop-up dialog box to drag

Click the pop-up dialog box to add an occlusion layer at the bottom. At the beginning, the occlusion layer is set to display: none
In the login dialog box, only the title part can be dragged to add a click Close label, which can be used to navigate to the upper right corner of the title line
Add a click event to the text pop-up dialog box, the login box and occlusion layer appear, and add a click event to the close icon
Implementation of drag and drop:
When we press the mouse, we get the position of the mouse in the box. When we move the mouse, we get the position of the mouse on the page - the position of the mouse in the box. When the mouse pops up, the mouse removes the event

Mouse events:
e.clientX returns the X coordinate of the mouse relative to the viewable area of the browser window
e.pageX returns the X coordinate of the mouse relative to the page document
element.offsetTop returns the offset above the parent element with relative positioning. Offset does not take units. It is read-only. It can only obtain the size and position of the element

<body> <div><a href="javascript:;" id="link">Click to pop up the dialog box</a></div> <div id="login"> <div>Login member <span><a id="closeBtn" href="javascript:void(0);">close</a></span> </div> <div> <div> <label for="">user name:</label> <input type="text" placeholder="enter one user name" id="username" name="info[username]"> </div> <div> <label for="">password:</label> <input type="password" placeholder="Please input a password" id="pasword" name="info[password]"> </div> <div id=loginBtn><a href="javascript:void(0);">Sign in</a></div> </div> </div> <!-- Covering layer --> <div id="bg"></div> <script> // 1. Click the pop-up dialog box to close the dialog box var login=document.querySelector('.login'); var mask=document.querySelector('.login-bg') var closeBtn=document.querySelector('.login-closeBtn'); var link=document.querySelector('#link'); var title=document.querySelector('.login-title') link.addEventListener('click',function(){ login.style.display='block'; mask.style.display='block'; }) closeBtn.addEventListener('click',function(){ login.style.display = 'none'; mask.style.display = 'none'; }) // 2. Start dragging // When we press the mouse, we get the position of the mouse in the box // When we move the mouse, we get the position of the mouse in the page - the position of the mouse in the box // Pop up the mouse to remove the event title.addEventListener('mousedown',function(e){ var x=e.pageX-login.offsetLeft;// Without unit var y=e.pageY-login.offsetTop; document.addEventListener('mousemove',move) function move(e) { login.style.left = e.pageX - x+'px'; login.style.top = e.pageY - y+'px'; } document.addEventListener('mouseup',function(e){ document.removeEventListener('mousemove',move) }) }) </script>

Moving end drag element

The principle is the same, and the event names are different
In touchstart event listening:
Get the initial position of the finger, startX = e.targetTouches[0].pageX
Initial position of the box x=this.offsetLeft

In touchmove event listening:
Calculate the moving distance of fingers, VAR MOVEX = e.targettouches [0]. Pagex startx; Get the current position of the box this.style.left=x+moveX + 'px';

Finger movement distance = position of the finger after sliding - position of the finger at the beginning
The current position of the box = the initial position of the box + the moving distance of the finger. Pay attention to the unit

<style> div { position: absolute; width: 200px; height: 200px; background-color: pink; margin: 100px auto; } </style> </head> <body> <div></div> <script> // Obtain the initial position of the finger touch and the initial position of the box var div = document.querySelector('div'); var startX = 0; var startY = 0; var x = 0; var y = 0; div.addEventListener('touchstart', function (e) { // Initial finger coordinates startX = e.targetTouches[0].pageX; startY = e.targetTouches[0].pageY; // The original position of the box x=this.offsetLeft; y=this.offsetTop; }); // Calculate the distance your fingers move and move the box div.addEventListener('touchmove',function(e){ // Where the finger slides - where the finger first touches var moveX=e.targetTouches[0].pageX-startX; var moveY = e.targetTouches[0].pageY - startY; // The original position of the box plus the distance your fingers move this.style.left=x+moveX+'px'; this.style.top=y+moveY+'px'; }); </script> </body>

Local storage - remember user name

After the page is opened, first judge whether there is data in the page localStorage.getItem, and save if there is. The check box is selected
When the check box is checked, localstore saves the data

<body> <input type="text" id="txtUserName"> <input type="password" name="" id="txtPassword"> <br> <input type="checkbox" name="" id="chkRemember"> Remember user name <script> window.onload = function () { //After the page opens var username = document.getElementById("txtUserName"); //Get user name var password = document.getElementById("txtPassword"); //Get password var chk = document.getElementById("chkRemember"); //Get remember login //If the page localStorage.getItem has data, save it and select the check box if (localStorage.getItem("username") && localStorage.getItem("password")) { username.value = localStorage.getItem("username"); password.value = localStorage.getItem("password"); chk.checked = true; } chk.onclick = function () { //Listen check box if (chk.checked) { //When selected, localStorage.setItem saves data localStorage.setItem("username", username.value); localStorage.setItem("password", password.value); } else { localStorage.removeItem("username"); //Delete localStorage.removeItem data when unchecked localStorage.removeItem("password"); } } } </script>

Rotation chart

index.html

<div> <!-- Left button --> <a href="javascript:;"> &lt; </a> <!-- Right button --> <a href="javascript:;">  </a> <!-- Core scrolling area --> <ul> <li> <a href="#"><img src="upload/focus.jpg" alt=""></a> </li> <li> <a href="#"><img src="upload/focus1.jpg" alt=""></a> </li> <li> <a href="#"><img src="upload/focus2.jpg" alt=""></a> </li> <li> <a href="#"><img src="upload/focus3.jpg" alt=""></a> </li> </ul> <!-- Small circle --> <ol> </ol> </div>

index.js

window.addEventListener('load', function() { // 1. Get element var arrow_l = document.querySelector('.arrow-l'); var arrow_r = document.querySelector('.arrow-r'); var focus = document.querySelector('.focus'); var focusWidth = focus.offsetWidth; // 2. After the mouse passes focus, the left and right buttons will be displayed and hidden focus.addEventListener('mouseenter', function() { arrow_l.style.display = 'block'; arrow_r.style.display = 'block'; clearInterval(timer); timer = null; // Clear timer variable }); focus.addEventListener('mouseleave', function() { arrow_l.style.display = 'none'; arrow_r.style.display = 'none'; timer = setInterval(function() { //Manually call click event arrow_r.click(); }, 2000); }); // 3. Dynamically generate small circles. If there are several pictures, I will generate several small circles var ul = focus.querySelector('ul'); var ol = focus.querySelector('.circle'); // console.log(ul.children.length);// 4 for (var i = 0; i < ul.children.length; i++) { // Create a small li var li = document.createElement('li'); // The index number of the current small circle is recorded through the user-defined attribute li.setAttribute('index', i); // Insert the small li into the ol ol.appendChild(li); // 4. The exclusive thought of small circles. We can directly bind click events while generating small circles li.addEventListener('click', function() { // Kill everyone and clear all small li current class names for (var i = 0; i < ol.children.length; i++) { ol.children[i].className = ''; } // Leave my current little li and set the current class name this.className = 'current'; // 5. Click the small circle to move the picture. Of course, the picture is ul // ul's moving distance is the index number of the small circle multiplied by the width of the picture. Note that it is a negative value // When we click a small li, we get the index number of the current small li var index = this.getAttribute('index'); // When we click a small li, we need to give the index number of the li to num num = index; // When we click a small li, we will give the index number of the li to the circle circle = index; // num = circle = index; console.log(focusWidth); console.log(index); animate(ul, -index * focusWidth); }) } // Set the first small li in ol to the class name current ol.children[0].className = 'current'; // 6. Clone the first picture (li) and put it at the back of ul var first = ul.children[0].cloneNode(true); ul.appendChild(first); // 7. Click the button on the right to scroll one picture var num = 0; // circle controls the playback of small circles var circle = 0; // flag throttle valve var flag = true; arrow_r.addEventListener('click', function() { if (flag) { flag = false; // Close the throttle valve // If we get to the last copied picture, our ul should quickly restore left to 0 if (num == ul.children.length - 1) { ul.style.left = 0; num = 0; } num++; animate(ul, -num * focusWidth, function() { flag = true; // Open the throttle valve }); // 8. Click the button on the right and the small circle will change together. You can declare another variable to control the playback of the small circle circle++; // If circle == 4, it means that at the end, we cloned the picture, and we will restore it if (circle == ol.children.length) { circle = 0; } // Call function circleChange(); } }); // 9. Method of left button arrow_l.addEventListener('click', function() { if (flag) { flag = false; if (num == 0) { num = ul.children.length - 1; ul.style.left = -num * focusWidth + 'px'; } num--; animate(ul, -num * focusWidth, function() { flag = true; }); // Click the button on the left and the small circle will change together. You can declare another variable to control the playback of the small circle circle--; // If circle < 0 indicates the first picture, the small circle should be changed to the fourth small circle (3) // if (circle < 0) { // circle = ol.children.length - 1; // } circle = circle < 0 ? ol.children.length - 1 : circle; // Call function circleChange(); } }); function circleChange() { // First clear the current class name of the remaining small circles for (var i = 0; i < ol.children.length; i++) { ol.children[i].className = ''; } // Leave the current class name of the current small circle ol.children[circle].className = 'current'; } // 10. Automatically play the rotation chart var timer = setInterval(function() { //Manually call click event arrow_r.click(); }, 2000); })

animate.js

function animate(obj, target, callback) { // console.log(callback); Callback = callback() when function() {} is called // First clear the previous timer and only keep the current timer for execution clearInterval(obj.timer); obj.timer = setInterval(function() { // The step value is written into the timer // Let's change the step value to an integer to avoid the problem of decimals // var step = Math.ceil((target - obj.offsetLeft) / 10); var step = (target - obj.offsetLeft) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); if (obj.offsetLeft == target) { // Stopping animation is essentially stopping the timer clearInterval(obj.timer); // The callback function is written to the end of the timer // if (callback) { // //Call function // callback(); // } callback && callback(); } // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10 obj.style.left = obj.offsetLeft + step + 'px'; }, 15); }

JS verification code

This part is reproduced from:

1. Digital SMS verification code
Idea: two text boxes, one button to obtain the verification code. The text box is used to enter the mobile phone number and the obtained verification code. The button is responsible for clicking and recording the countdown
JS writes the timer settimeput to record the expiration time of the verification code for 60 seconds
The background provides an interface for SMS acquisition and verification. We pass the mobile phone number as a parameter, obtain the mobile phone number the day after tomorrow, and issue the verification code

HTML

<input type="text" name="phone" id="phone" value="" placeholder="Please enter your mobile phone number" maxlength="11" /> <input type="" name="verCode" id="verCode" value="" placeholder="Please enter the verification code" maxlength="6"/> <input type="button" name="" id="verCodeBtn" value="Get verification code" onclick="settime(this);"/>

Countdown JS

//Verification Code var counts = 60; function settime(val) { if(counts == 0) { val.removeAttribute("disabled"); val.value = "Get verification code"; counts = 60; return false; } else { val.setAttribute("disabled", true); val.value = "Resend(" + counts + ")"; counts--; } setTimeout(function() { settime(val); }, 1000); }

Ajax interface code

$(function(){ //Get verification code $("#verCodeBtn").click(function() { var userinfo = { "UserPhoneNum": '86//' + $("input[name='phone']").val() } $.ajax({ url: "https://www.xxxxx.cn/user/sendcode/", data: userinfo, type: "get", success: function(data) { if(JSON.parse(data).state === 404 || JSON.parse(data).state === 202 || userinfo.UserPhoneNum === '86//') { alert("Verification code sending failed") } else { alert("The verification code was sent successfully. Please wait patiently") } }, error: function() { alert("fail in send"); } }); }); })

2. Graphic verification code
Idea:

a. A text box is used to input the verification code composed of numbers and letters + a canvas label to display the graphic verification code + a submit button;
b. Submit button to verify the form, and prompt for correct or wrong input;
c. Generate and render verification code graphics with canvas, and obtain random color values;

html

<div> <input type="text" value="" placeholder="Please enter the verification code (case insensitive)"> <canvas id="canvas" width="100" height="30"></canvas> <button>Submit</button> </div>

css

<style> .input-val { width: 200px; height: 32px; border: 1px solid #ddd; box-sizing: border-box; } #canvas { vertical-align: middle; box-sizing: border-box; border: 1px solid #ddd; cursor: pointer; } .btn { display: block; margin-top: 20px; height: 32px; width: 100px; font-size: 16px; color: #fff; background-color: #457adb; border: none; border-radius: 50px; } </style>

js

<script type="text/javascript" src="js/jquery-3.3.1.min.js" ></script> <script> $(function(){ var show_num = []; draw(show_num); $("#canvas").on('click',function(){ draw(show_num); }) $(".btn").on('click',function(){ var val = $(".input-val").val().toLowerCase(); var num = show_num.join(""); if(val==''){ alert('Please enter the verification code!'); }else if(val == num){ alert('Submitted successfully!'); $(".input-val").val(''); // draw(show_num); }else{ alert('Verification code error! Please re-enter!'); $(".input-val").val(''); // draw(show_num); } }) }) //Generate and render verification code graphics function draw(show_num) { var canvas_width=$('#canvas').width(); var canvas_height=$('#canvas').height(); var canvas = document.getElementById("canvas");//Get the object of canvas, actor var context = canvas.getContext("2d");//Get the canvas drawing environment and the stage where the actors perform canvas.width = canvas_width; canvas.height = canvas_height; var sCode = "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0"; var aCode = sCode.split(","); var aLength = aCode.length;//Gets the length of the array for (var i = 0; i < 4; i++) { //The for loop here can control the number of verification code digits (if you want to display 6 digits, change 4 to 6) var j = Math.floor(Math.random() * aLength);//Get random index value // var deg = Math.random() * 30 * Math.PI / 180; / / generate random radians between 0 and 30 var deg = Math.random() - 0.5; //Generate a random radian var txt = aCode[j];//Get a random content show_num[i] = txt.toLowerCase(); var x = 10 + i * 20;//x coordinate of text on canvas var y = 20 + Math.random() * 8;//y coordinate of text on canvas context.font = "bold 23px Microsoft YaHei "; context.translate(x, y); context.rotate(deg); context.fillStyle = randomColor(); context.fillText(txt, 0, 0); context.rotate(-deg); context.translate(-x, -y); } for (var i = 0; i <= 5; i++) { //Display line on verification code context.strokeStyle = randomColor(); context.beginPath(); context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height); context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height); context.stroke(); } for (var i = 0; i <= 30; i++) { //Small dots are displayed on the verification code context.strokeStyle = randomColor(); context.beginPath(); var x = Math.random() * canvas_width; var y = Math.random() * canvas_height; context.moveTo(x, y); context.lineTo(x + 1, y + 1); context.stroke(); } } //Get random color values function randomColor() { var r = Math.floor(Math.random() * 256); var g = Math.floor(Math.random() * 256); var b = Math.floor(Math.random() * 256); return "rgb(" + r + "," + g + "," + b + ")"; } </script>

3. Sliding verification code
Logic is to judge whether human operation is carried out according to the mouse sliding track, coordinate position, calculated drag speed, etc
Idea:
a. It is composed of three div, which constitutes the effect of slider and bottom progress bar;
b. Write js, register mouse press, suspend and release events;
c. Record the moving distance and status of the slider to judge whether it is successful

<div> <div></div> <div onselectstart="return false;">Please drag the slider to unlock</div> <div>&gt;&gt;</div> </div>
<style> .drag{ width: 300px; height: 40px; line-height: 40px; background-color: #e8e8e8; position: relative; margin:0 auto; } .bg{ width:40px; height: 100%; position: absolute; background-color: #75CDF9; } .text{ position: absolute; width: 100%; height: 100%; text-align: center; user-select: none; } .btn{ width:40px; height: 38px; position: absolute; border:1px solid #ccc; cursor: move; font-family: "Song typeface"; text-align: center; background-color: #fff; user-select: none; color:#666; } </style>

20 September 2021, 22:08 | Views: 3348

Add new comment

For adding a comment, please log in
or create account

0 comments