如何仅在字幕溢出时制作字幕文本? [英] How to make marquee text only when it's overflowing?

查看:104
本文介绍了如何仅在字幕溢出时制作字幕文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个随机生成到div的文本。并且此文本的宽度取决于当前生成的内容。而且我希望此文本仅在太大时才显示为 html:

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

我已经在互联网上找到此CSS属性: overflow -x:-webkit-marquee;
,但是我不确定如何使用它。有人可以帮忙吗?

I found already this css property in internet: overflow-x:-webkit-marquee; but I'm not sure how to use it. Can anyone help?

推荐答案

确定元素是否溢出的最简单方法是比较其滚动高度/宽度为其偏移量的高度/宽度。如果任何 scroll 值大于它们的 offset 对,则元素的内容溢出。

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);
}

从这里开始,这是一个简单的问题,需要检查此函数的返回值并添加如果 true 是字幕效果。为此,您可以将div的内容包装在< marquee> 中,或使用带前缀的 marquee CSS规则或通过CSS动画对其进行模拟。

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:而< marquee> 标记仍可在大多数浏览器中按预期方式工作,已被认为已弃用,因此不能保证未来的发展。

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

祝你好运!

这篇关于如何仅在字幕溢出时制作字幕文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆