search
HomeWeb Front-endJS TutorialIntroduction 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

Introduction to three ways to implement text ticker (code examples)

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(&#39;.box&#39;),
  document.querySelector(&#39;.content&#39;),
  document.querySelector(&#39;.text&#39;)
]
let [textWidth, boxWidth] = [
  text.offsetWidth,
  box.offsetWidth
]
window.onload=function checkScrollLeft(){
  // 判断文字长度是否大于盒子长度
  if(boxWidth > textWidth){ return false}
  content.innerHTML += content.innerHTML
  document.querySelector(&#39;.text&#39;).classList.add(&#39;padding&#39;)
  // 更新
  textWidth = document.querySelector(&#39;.text&#39;).offsetWidth
  toScrollLeft()
}
function toScrollLeft(){
  //  如果文字长度大于滚动条距离,则递归拖动
  if(textWidth > box.scrollLeft){
    box.scrollLeft++
    setTimeout(&#39;toScrollLeft()&#39;, 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:

Introduction to three ways to implement text ticker (code examples)

Code part:

  <marquee>1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</marquee>

Very concise code~,~

marquee’s API

Introduction to three ways to implement text ticker (code examples)

##Although the API of the marquee tag is very rich, the tag is not available on MDN Described like this:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

elements It is obsolete, please do not use it anymore. Although some browsers still support it, it's not required. Also, using this element is basically one of the worst things you can do to your users, so please don't do it.

Therefore, according to the principle of closely following document standards in our IT circle, we please try not to use the marquee tag in our projects

3. CSS implementation

Rendering

Introduction to three ways to implement text ticker (code examples)

Code part

HTML:


<div class="wrap">
  <div class="cont">
    <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p>
    <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p>        
  </div>
</div>

CSS:

*{
  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;
}

JS:

var cont = document.querySelector(&#39;.cont&#39;)
var wrap = document.querySelector(&#39;.wrap&#39;)
var text = document.querySelector(&#39;.txt&#39;)
var wrapWidth = wrap.offsetWidth
var textWidth = text.offsetWidth
window.onload=function checkScrollLeft(){
  // 判断文字长度是否大于盒子长度  开始滚动
  if(textWidth > wrapWidth) {
    text.style.paddingRight = &#39;300px&#39;
    cont.style.left = "-870px"
  }
  // 滚动结束
  document.addEventListener("transitionend", function (){
    console.log("end")
  }, false)
}

Summary

CSS can meet sub-need point 1 and can determine when to start scrolling.

window.onload=function checkScrollLeft(){
  // 判断文字长度是否大于盒子长度
  if(textWidth > wrapWidth) {
    // 开始滚动  触发事件
    text.style.paddingRight = '300px'
    cont.style.left = "-870px"
  }
}
At the same time, it can also meet sub-demand point 2 and determine the end of scrolling.

// 滚动结束
document.addEventListener("transitionend", function (){
    console.log("end")
}, false)

Conclusion

Review of requirements

Requirement 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 methods

js realizes the marquee effecthtml realizes the marquee effectcss realizes the marquee effect EffectDemand point 1✔️✘✔️Requirement point 2✔️✘✔️Compatibility✔️ ✘✘

If you need to meet the requirements, both js and css can be implemented. However, considering compatibility, CSS is not supported below ios9 and below Android 4.4. Other good solutions are under consideration. If you have a good solution, please leave a message below to communicate with me~

In addition, CSS can still be given priority if it is used for pure display effects, such as the CSS seamless scrolling below

Rendering

Introduction to three ways to implement text ticker (code examples)

Code part

HTML:

<div class="wrap">
  <div class="cont">
    <p class="txt">1.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p>
    <p class="txt">2.文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p>
  </div>
</div>

CSS:

*{
  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%;
  }
}

So, the tool itself has no advantages Which tool should be used when? We need to have clear ideas.

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool