Use JavaScript to implement comment and like functions
By analyzing the logical relationship of the comment function, learn how to use JavaScript to implement various functions such as comments, replies, and likes. This article mainly introduces how to implement the JavaScript comment and like function. Friends who need it can refer to
By analyzing the logical relationship of the comment function, you can learn how to use Javascript to implement various functions such as comments, replies, and likes.
1. Learn how to handle date and time with Javascript.
2. Master the method of adding/deleting child nodes in Dom operations.
3. Use setTimeout to set the timer.
4. Use clearTimeout to clear the timer and use the event agent.
Rendering:
1) Implement the function of deleting shared content
Use the event proxy to delete the shared content by clicking the close button.
Delete events:
Use the event proxy function to add events on the parent element node to reduce the amount of code and system running load.
When event proxying, use events The srcElement attribute in the object gets the trigger element.
IE browser supports window.event.srcElement, and firefox supports window.event.target.
So, if you want to be compatible in firefox, you only need to change one code: change var el = e.srcElement to var el = e.srcElement || e.target
removeChild() refers to Delete the child element, so to delete the current element el, first use parentNode to find the parent node, and then use removeChild(el) to delete the el element.
var list = document.getElementById('list'); var boxs = document.getElementsByClassName('box'); //删除节点函数 function removeNode(node){ node.parentNode.removeChild(node); } //事件代理 for(var i=0 ;i<boxs.length;i++){ boxs[i].onclick = function(e){ e = e||window.event; var el = e.srcElement || e.target; switch (el.className) { case 'close':removeNode(el.parentNode);break; } } }
2) Implement the like function of sharing
Constructing a like and share function requires two parameters. The first parameter (box) represents the outermost parent of the like. Container, the second parameter (el) refers to the triggered element, that is, the like button
getAttribute() to get the attributes, and use setAttribute() to set the attributes of the element.
js code:
//点赞分享 function praiseBox(box,el){//box为所触发元素el的最外层父容器 var praiseElement = box.getElementsByClassName('praise-total')[0]; var oldTotal = parseInt(praiseElement.getAttribute('total')); var txt = el.innerHTML; var newTotal = 0; if(txt == '赞'){ newTotal = oldTotal + 1; praiseElement.innerHTML = (newTotal == 1) ? '我觉得很赞' : '我和' + oldTotal +'个人觉得很赞'; el.innerHTML = '取消赞'; }else{ newTotal = oldTotal - 1; praiseElement.innerHTML = (newTotal == 0) ? '' : newTotal + '个人觉得很赞'; el.innerHTML = '赞'; } praiseElement.setAttribute('total',newTotal); praiseElement.style.display = (newTotal == 0) ? 'none': 'block'; } //事件代理 for(var i=0 ;i<boxs.length;i++){ boxs[i].onclick = function(e){ e = e||window.event; var el = e.srcElement || e.target; switch (el.className) { case 'close':removeNode(el.parentNode);break; case 'praise':praiseBox(el.parentNode.parentNode.parentNode,el); } } }
3) Implement the comment function
First of all, you must implement the change of the comment input box, by listening to three events
1. Obtain When the focus is on: onfocus
2. When the focus is lost: onblur
3. When the mouse input pops up: onkeyup
//输入框 var textarea = boxs[i].getElementsByTagName('textarea')[0]; textarea.onfocus = function(){ this.parentNode.className = 'text-box text-box-on'; this.value = (this.value == '评论...') ? '':this.value; } textarea.onblur = function(){ if(this.value == ''){ this.parentNode.className = 'text-box'; this.value = '评论...'; } }
4) Implement the reply button and word count functions
Add the onkeyup keyboard pop-up event to the textarea and learn to use the method of obtaining the parent node and child node.
In order to provide a better user experience, the input box will not immediately become smaller when it loses focus, so add a timer function in onblur. Note that the timer must be cleared when the gray reply button is clicked
js code:
textarea.onblur = function(){ var me = this;//因为有定时器所以先将this存放于变量中 timer = setTimeout(function(){ if(me.value == ''){ me.parentNode.className = 'text-box'; me.value = '评论...'; } },500); } textarea.onkeyup = function(){ var len = this.value.length; var p = this.parentNode; var btn = p.children[1]; var word = p.children[2]; if(len == 0 || len > 140){ btn.className = 'btn btn-off'; }else{ btn.className = 'btn'; } word.innerHTML = len + '/140'; }
5) Implement the comment sharing function
When the reply button is clicked, the content of the input box is added to the reply list by creating a p and adding a reply list, pay attention to changing part of the new reply list and the date of the comment to be changed.
js code:
//发表评论 function replayBox(box){ var textarea = box.getElementsByTagName('textarea')[0]; var list = box.getElementsByClassName('comment-list')[0]; var p = document.createElement('p'); p.className = 'comment-box clearfix'; p.setAttribute('user','self'); var html = ' <img src="images/my.jpg" class="myhead" alt="" />'+ '<p class="comment-content">'+ '<p class="comment-text"><span class="user">我:</span>'+textarea.value+'</p>'+ '<p class="comment-time">'+ getTime()+ '<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-praise" total="0" my="0" style="">赞</a>'+ '<a href="javascript:;" rel="external nofollow" rel="external nofollow" class="comment-operate">删除</a>'+ '</p>'+ '</p>'; p.innerHTML = html; list.appendChild(p); textarea.value = ''; textarea.onblur(); function getTime(){ var t = new Date(); var y = t.getFullYear(); var m = t.getMonth() + 1;//月份是从0开始 var d = t.getDay(); var h = t.getHours(); var mi = t.getMinutes(); m = m>10 ? m: '0' + m; d = d>10 ? d: '0' + d; h = h>10 ? h: '0' + h; mi = mi>10 ?mi: '0' +mi; return y + '-' + m + '-' + d + ' ' + h + ':' + mi; } }
5) Implement the like reply function
There is a my attribute in the a tag of the like button, which indicates whether you have liked it. When my When the value is 0, total will increase by one when the like button is clicked. When my value is 1, total will decrease by one when the like button is clicked.
js code:
//点赞回复 function praiseReplay(el){ var oldTotal = parseInt(el.getAttribute('total')); var my = parseInt(el.getAttribute('my')); var newTotal = 0; if(my == 0){ newTotal = oldTotal + 1; el.setAttribute('total',newTotal); el.setAttribute('my',1); el.innerHTML = newTotal + '取消赞'; }else{ newTotal = oldTotal - 1; el.setAttribute('total',newTotal); el.setAttribute('my',0); el.innerHTML = (newTotal == 0) ? '' : newTotal + '赞'; } el.style.display = (newTotal == 0) ? '' : 'inline-block'; }
6) Implement the deletion and reply function of the content in the reply list
Reply to other people’s comments and delete your own comments
js code:
//操作回复 function operateReply(el){ var commentBox = el.parentNode.parentNode.parentNode;//评论的容器 var box = commentBox.parentNode.parentNode.parentNode;//该条分享的容器 var textarea = box.getElementsByTagName('textarea')[0]; var user = commentBox.getElementsByClassName('user')[0]; var txt = el.innerHTML; if(txt == '回复'){ textarea.onfocus(); textarea.value = '回复' + user.innerHTML; textarea.onkeyup(); } else{ removeNode(el.parentNode.parentNode.parentNode); } }
The above is the detailed content of Use JavaScript to implement comment and like functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
