如何在选择时仅将背景颜色应用于文本的一半? [英] How to apply a background color to only half of the text on selecting?

查看:74
本文介绍了如何在选择时仅将背景颜色应用于文本的一半?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我选择文本时,背景颜色变为黄色.

When I select text, the background color changes to yellow.

body p::selection {
  background: #fcf113;
  color: #000;
  display: none;
}
body p::-moz-selection {
  background: #fcf113;
}

但是,我希望它看起来像这样.

But, I want it to appear like this.

有可能吗?

推荐答案

感谢您破坏了我至少一天的时间,但实际上我找到了一个仅CSS的解决方案.虽然它不是很可靠,而且涉及很多伪造,但是请注意:没有JavaScript!

Thank you for ruining at least an hour of my day, but I actually found a CSS-only solution. It's not really solid though, and it involves a lot of faking, but hey: No JavaScript!

我们基本上使用与范围保持相同内容的data-content属性,然后将其复制到显示它的分层:after元素中.然后,我们隐藏原始文本,并将50%的高度应用于after元素,这样背景颜色只能应用于下半部分.

We basically use a data-content attribute with the same content as the span holds, and then copy this to a layered :after element which displays it. We then hide the original text and apply a 50% height to the after element, this way the background color can only be applied to the bottom half.

h1 {
    position: relative;
    color: #FFF;
}

h1:after {
    content: attr(data-content);
    position: absolute;
    color: #000;
    top: 0;
    left: 0;
    width: 100%;
    height: 50%;
    background-color: #FFF;
}

h1::selection {
    background: #fcf113;
}

<h1 data-content="Hello world!">Hello world!</span>

基于上述内容,用户@chrona制作了这个非常可爱的工作版本:

Based on above, user @chrona made this really lovely working version:

var paragraph = $('p');
var words     = paragraph.text().split(" ");

paragraph.empty();

$.each(words, function(i, v) {
    paragraph.append('<span data-word="' + v + '"> ' + v + ' </span>');
});

p {
  background: white;
}

body {
  background: white;
}

span {
  position: relative;
  font-size: 1.25rem;
  line-height: 1.4;
}

span::after {
  background: white;
  content: attr(data-word);
  display: block;
  height: 75%;
  left: 0;
  padding-top: 0.14em;
  position: absolute;
  pointer-events: none;
  overflow: hidden;
  top: -0.28em;
  width: 100%;
}

span::selection {
  background: #fcf113;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>

这篇关于如何在选择时仅将背景颜色应用于文本的一半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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