根据页面的位置突出显示文本中的字符

highlighting characters in text depending on position of page

本文关键字:显示 文本 字符 位置      更新时间:2023-09-26

我的网站上有一个文本,它在页面中水平滚动。我试着用黑色突出显示大约8个字符,而其余的是灰色。但这些字符意味着随着滚动而变化,不过突出显示的部分应该保持不变。

如果这没有任何意义,如果灰色是一个x,它应该看起来像这样:

xxxxx xpsum dolox xxx-xxxx
xxxx-xxsum dolox sxx-xxxx-xxxx
xxx xxxum dolox six xxxx
xx xxxxm邮箱地址xxxx-xx

我正试图在jQuery中完成这项工作,但我无法让它发挥作用。我还想说,我根本不是网络设计专家,所以我不知道自己在做什么。无论如何,我尝试了两种不同的方法,一种是说"在遍历底层div时更改文本的颜色"。另一种方法是根据滚动位置更改文本的颜色,但这里的问题是它占用了整个div的滚动位置,而不是页面上的固定位置。两者目前都不起作用,示例如下:

jsfiddle 9p29tz2fjsfiddle 9p29tz2f/1

如果有人对此有任何想法,或者需要更多澄清,请告诉我。非常感谢!

克隆文本并将其设置为覆盖框的子项,然后将它们滚动到一起:

$(function(){
    var $bodytext = $('#bodytext'),
        $clone = $bodytext.clone();         
    //copy the text and append it to #black:
    $clone.attr("id","clone").prependTo("#black");
    //scroll #clone with #bodytext:
    $bodytext.scroll(function(){
        $clone.scrollLeft($bodytext.scrollLeft());
    });
});

http://jsfiddle.net/9p29tz2f/2/

我采用了Teemu的解决方案并对其进行了一些修改:http://jsfiddle.net/9af91wcL/2/

重要的部分:代码在文本顶部移动一个白色DIV(#grey-overlay),使其透明。通过添加黑色和白色像素,可以得到灰色。灰度级由alpha通道确定(rgba()函数中为0.7)。

你需要指定一个高度,否则看起来会很奇怪。我使用1.5em来确保它不会与#bodytext分区的滚动条重叠。

还要确保两个div的顶部/左侧位置相同。

在您的真实代码中,您可以使用JavaScript使水平滚动条消失并滚动。

HTML

<div id="grey-overlay"></div>
<div id="bodytext">text...</div>

CSS

body {
    background: #ffffff;
    color: #000000;
    font-family: sans-serif;
    font-size: 200%;
}
#bodytext {
    top: 15%;
    width:200px;
    height: 2em;
    padding: 0;
    position:absolute;
    overflow-x:scroll;
    overflow-y:hidden;
    white-space: nowrap;
}
#grey-overlay {
    background-color: rgba(255, 255, 255, 0.7);
    width:40px;
    height: 1.5em;
    top:15%;
    position:fixed;
    z-index: 10;
}

您需要在#black中显示与#bodytext中相同的内容,并同步其相对于#bodytext滚动的位置。这可以通过在#black周围使用额外的包装器来实现。类似这样的东西:

CSS:

#cover {
    top: 15%;
    height:50%;
    width: 120px;
    padding: 0;
    position:fixed;
    overflow-x: hidden;
    background-color: #D8D8D8;
}
#black {
    color: #000000;
    width:100%;
    height:100%;
    top:0px;
    left: 0px;
    position:absolute;
    white-space: nowrap;
    z-index: 10;
}
#bodytext {
    top: 15%;
    width:100%;
    height:85%;
    padding: 0;
    position:absolute;
    overflow-x:scroll;
    white-space: nowrap;
    color: #D8D8D8;
}

HTML:

<div id="cover">
    <div id="black"></div>
</div>

JS:

$(document).ready(function () {
    var black = $('#black'),
        btext = $('#bodytext');
    black.text(btext.text()); // Clone the content
    btext.scroll(function () {
        var pos = btext.scrollLeft();
        black.css('left', -pos + 'px'); // Set the position to match #bodytext
    });
});

jsFiddle的现场演示。

请注意,如果您需要一些左边距,还必须"计算"到pos