问题
I have a text which is generated randomly to a div. And this text has different width depending on what is currently generated. And I want this text to marquee only when is too big. html:
<div id="random_word"> <!--here appears something--> </div>
css:
#random_word {
color: white;
position: absolute;
width: 50%;
left: 0%;
text-align: center;
font-size: 8vw;
margin-top: 22%;
font-variant: small-caps
text-shadow: 0 0 20px #000;
text-align: center;
z-index: 2;
overflow: hidden;
white-space: nowrap;
line-height: 100%;
}
I found already this css property in internet: overflow-x:-webkit-marquee;
but I'm not sure how to use it. Can anyone help?
回答1:
The easiest way to determine if an element is overflowing is to compare its scroll
height/width to its offset
height/width. If any of the scroll
values are larger than their offset
pairs, your element's contents are overflowing.
function isElementOverflowing(element) {
var overflowX = element.offsetWidth < element.scrollWidth,
overflowY = element.offsetHeight < element.scrollHeight;
return (overflowX || overflowY);
}
From here it's a simple question of checking the return value of this function and adding a marquee effect if true
. To achieve this, you can wrap your div's contents in a <marquee>
, or achieve the same visual effect using the prefixed marquee
CSS rules or simulating it via a CSS animation.
NB: while the <marquee>
tag still works as expected in most browsers, it is considered deprecated hence not futureproof.
- Here is a quick fiddle on wrapping in a marquee tag, play around with text length to see how it works. (alternatively, you can set the marquee's behavior to alternate from side to side: here's how )
- here is a tutorial on CSS marquee
- and here is a thread on visually simulating a marquee with animations
Good luck!
来源:https://stackoverflow.com/questions/41987383/how-to-make-marquee-text-only-when-its-overflowing