jQuery:根据包含元素的背景颜色更改文本颜色?

发布于 2024-11-25 05:34:42 字数 277 浏览 4 评论 0原文

我想根据元素的背景颜色更改元素的文本颜色。

例如,如果背景颜色更改为黑色,则将文本设置为白色。如果背景颜色更改为白色,则将文本设置为黑色。

尽管用户可以将背景颜色更改为他们想要的任何颜色,但它会比这更复杂一些。

我发现了一些关于在后端处理它的随机文章,但没有使用javascript(或更好的是,jQuery)。

I want to change the text color of an element based on the element's background color.

For instance, if the background color is changed to black, then make the text white. If the background color is changed to white, then make the text black.

It'd be a bit more complex than than that though as the user can change the background color to whatever they'd like.

I found some random articles about handling it on the backend, but nothing using javascript (or better yet, jQuery).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海夕 2024-12-02 05:34:42

首先,创建一个函数来确定颜色是否为深色(,修改):

function isDark( color ) {
    var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
    return parseFloat(match[1])
         + parseFloat(match[2])
         + parseFloat(match[3])
           < 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
}

然后,使用以下内容:

$('elem').each(function() {
    $(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
});

http://jsfiddle.net/QkSva/

First, create a function that determines whether a color is dark or not (source, modified):

function isDark( color ) {
    var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
    return parseFloat(match[1])
         + parseFloat(match[2])
         + parseFloat(match[3])
           < 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
}

Then, use something along the lines of:

$('elem').each(function() {
    $(this).css("color", isDark($(this).css("background-color")) ? 'white' : 'black');
});

http://jsfiddle.net/QkSva/

无需解释 2024-12-02 05:34:42

我建议你使用 css 主题,因此更改为 css 文件。但你可以用 jQuery 来做到这一点。

<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
    $().ready(function () {
        var color = $("body").css("backgroundColor");
        if (color == "...")
            $("body").css("color", "...");
    });
</script>

这只是简单的解决方案,如果你真的想要这个,最好设置
背景变化的事件。

希望有帮助

I suggest you do use css theming, so change to css file, for that. But you can do it with jQuery.

<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
    $().ready(function () {
        var color = $("body").css("backgroundColor");
        if (color == "...")
            $("body").css("color", "...");
    });
</script>

this is only the simple solution, if you really want to this it would be good to set
a event on background changes.

hope that helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文