Introduction to three ways to implement text ticker (code examples)
What this article brings to you is an introduction to three ways to implement text marquees (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I recently wrote a project requirement for a text marquee. I just started writing it in js and was able to complete the requirement. Later, I thought about using another method (html and css respectively) to achieve the same requirement to reduce performance consumption.
First, demand analysis:
Requirement point 1. Determine the length of the text and the length of the container. If the length of the text is greater than the length of the container, start scrolling, otherwise it will not scroll;
Demand point 2. Determine the end of scrolling and trigger events at the end time (for example: adding or subtracting styles, etc.);
1. JS implementation
Thinking :
1. Determine the length of the text and the length of the container. If the length of the text is greater than the length of the container, start scrolling, otherwise it will not scroll. (offsetWidth)
2. Get the distance from the scroll bar to the left side of the element, and scroll recursively until the scrolled distance is equal to the length of the text and exit the recursion. (scrollLeft)
Rendering
Note: The text jitter phenomenon is due to the long recording time, and the GIF file produced by PS can only be 500 frames Below, text jitter appears by lowering the frame rate.
Code part
HTML:
<div class="box"> <div class="content"> <p class="text">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> </div> </div>
CSS:
*{ margin:0; padding:0; } .box{ margin-left: 200px; margin-top: 100px; color: #FFF; white-space: nowrap; overflow: hidden; width: 300px; background: #000; } .content p{ display:inline-block; } .content p.padding{ padding-right: 300px; }
JS:
let [box, content, text] = [ document.querySelector('.box'), document.querySelector('.content'), document.querySelector('.text') ] let [textWidth, boxWidth] = [ text.offsetWidth, box.offsetWidth ] window.onload=function checkScrollLeft(){ // 判断文字长度是否大于盒子长度 if(boxWidth > textWidth){ return false} content.innerHTML += content.innerHTML document.querySelector('.text').classList.add('padding') // 更新 textWidth = document.querySelector('.text').offsetWidth toScrollLeft() } function toScrollLeft(){ // 如果文字长度大于滚动条距离,则递归拖动 if(textWidth > box.scrollLeft){ box.scrollLeft++ setTimeout('toScrollLeft()', 18); } else{ // setTimeout("fun2()",2000); } }
Summary
The js method can perfectly satisfy sub-need point 1 and self-need point 2.
The length of text and container can be judged by offsetWidth. If the text is longer than the container, scrolling begins.
window.onload=function checkScrollLeft(){ // 判断文字长度是否大于盒子长度 if(boxWidth >= textWidth){ return false} content.innerHTML += content.innerHTML document.querySelector('.text').classList.add('padding') // 更新 textWidth = document.querySelector('.text').offsetWidth // 开始滚动 触发事件 toScrollLeft() }
Judge the end of scrolling based on the distance from the scroll bar to the left side of the element and the length of the text. If the distance from the scroll bar to the left side of the element is equal to the length of the text, the scrolling will end.
function toScrollLeft(){ // 如果文字长度大于滚动条距离,则递归拖动 if(textWidth > box.scrollLeft){ box.scrollLeft++ setTimeout('toScrollLeft()', 18); } else{ // 滚动结束 触发事件 } }
2. HTML implementation
Rendering:
Code part:
<marquee behavior="behavior" width="200" loop="2">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</marquee>
Very concise code~,~
marquee’s API
3. CSS implementation
Rendering<div class="wrap"> <div class="cont"> <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> </div> </div>
*{ padding: 0; margin: 0; box-sizing: border-box; } .wrap{ margin:10% auto; background: #ddd; font-size: 0; /* 固宽,溢出隐藏 */ width: 300px; height: 40px; overflow: hidden; white-space: nowrap; /* 相对定位 */ position: relative; } .wrap .cont{ position: absolute; top: 0; left: 0; height: 100%; /* 关键 */ width: 200%; transition:left 10s linear; } .wrap .txt{ display: inline-block; font-size: 18px; line-height: 30px; margin-top: 5px; color: #fff; background: #000; }
var cont = document.querySelector('.cont') var wrap = document.querySelector('.wrap') var text = document.querySelector('.txt') var wrapWidth = wrap.offsetWidth var textWidth = text.offsetWidth window.onload=function checkScrollLeft(){ // 判断文字长度是否大于盒子长度 开始滚动 if(textWidth > wrapWidth) { text.style.paddingRight = '300px' cont.style.left = "-870px" } // 滚动结束 document.addEventListener("transitionend", function (){ console.log("end") }, false) }
window.onload=function checkScrollLeft(){ // 判断文字长度是否大于盒子长度 if(textWidth > wrapWidth) { // 开始滚动 触发事件 text.style.paddingRight = '300px' cont.style.left = "-870px" } }
// 滚动结束 document.addEventListener("transitionend", function (){ console.log("end") }, false)
Conclusion
Review of requirementsRequirement point 1. Determine the length of the text and the length of the container. If the text length is greater than the container length, start scrolling , otherwise it will not scroll; Requirement point 2. Determine the end of scrolling and trigger events at the end time (for example: adding or subtracting styles, etc.);Comparison of the advantages and disadvantages of implementation methodshtml realizes the marquee effect | css realizes the marquee effect Effect | ||
---|---|---|---|
✔️ | ✘ | ✔️ | |
✔️ | ✘ | ✔️ | |
✔️ | ✘ | ✘ |
<div class="wrap"> <div class="cont"> <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> <p class="txt">2.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> </div> </div>
*{ padding: 0; margin: 0; box-sizing: border-box; } .wrap{ position: relative; width: 40%; height: 40px; margin:10% auto; background: #ddd; font-size: 0; overflow: hidden; } .wrap .cont{ position: absolute; top: 0; left: 0; /* 宽度 大于容器的两倍即可 */ width: 200%; -webkit-animation:5s move infinite linear; } .wrap .txt{ font-size: 18px; color: #fff; display: inline-block; /* 宽度 等于容器的宽度 */ width: 50%; height: 30px; border-left:1px solid #fff; line-height: 30px; text-align: center; margin-top: 5px; background: #000; } .wrap:hover .cont{ -webkit-animation-play-state:paused; } @-webkit-keyframes move{ /* 原理 left值的变化 移动一个容器的宽度 */ 0%{ left: 0; } 100%{ left: -100%; } }
The above is the detailed content of Introduction to three ways to implement text ticker (code examples). 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

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo
