【问题标题】:Jquery: Link text color to random background imageJquery:将文本颜色链接到随机背景图像
【发布时间】:2013-06-24 01:37:00
【问题描述】:

每次刷新窗口时,我都会使用 jQuery 为我的网页随机分配一个背景图像。我想为每个背景分配一个相应的文本颜色。

我正在尝试使用此代码,但没有运气:

$(document).ready(function () {
    var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];

    $('body').css({
        'background-image': 'url(img/' + images[Math.floor(Math.random() * images.length)] + ')'
    });

    if ($('body').css('background-image') === 'img/5.jpg') {
        $('#intro').css('color', 'red!important');
    };
});

【问题讨论】:

  • 每次刷新窗口,一切都会丢失,你必须使用localStorage或cookies。
  • 为什么不将随机数放入一个变量中,然后在 if 中使用该变量(而不是尝试检索您之前分配的背景图像)?

标签: jquery css random


【解决方案1】:

.css('background-image') 返回一个用url() 包裹的图像 URL。我会改用一个对象数组:

var themes = [{
    image: '1.jpg',
    color: 'red'
}, {
    image: '2.jpg',
    color: 'orange'
}];

现在,你可以这样做了:

var theme = themes[Math.floor(Math.random() * themes.length)];

$('body').css({
    'background-image': 'url("img/' + theme.image + '")',
    'color': theme.color
});

【讨论】:

    【解决方案2】:

    为什么不更新你的images 数组,让每个元素实际上是一个“背景/文本颜色”数组 - 像这样:

    var images = [['1.jpg', '#000'], ['2.jpg', '#111'], ['3.jpg', '#222'], ['4.jpg', '#333'], ['5.jpg', '#444'], ['6.jpg', '#555']];
    var random = Math.floor(Math.random() * images.length)]
    $(body).css({
        'background-image': 'url(img/' + images[random][0] + ')',
        'color':            images[random][1]
    });
    

    【讨论】:

      【解决方案3】:

      尝试输入console.log($('body').css('background-image')) 以查看返回此内容的内容。我认为这是返回类似 url(img/5.jpg) 而不是 img/5.jpg

      如果将随机事物设置为变量,然后与该变量而不是 css 属性进行比较,也可能更容易

      【讨论】:

        【解决方案4】:

        我会这样做:

        var styles = [
            { image: '1.jpg', color: 'blue' },
            { image: '2.jpg', color: 'green' },
            ...
        ];
        
        var style = styles[Math.floor(Math.random() * styles.length)];
        $(body).css{ 'background-image': 'url(img/' + style.image + ')',
                     'color': style.color + '!important' });
        

        但是,您的代码的基本问题是,当您与现有样式进行比较时,您忘记了url(...),它应该是:

        if ($('body').css('background-image') === 'url(img/5.jpg)') {
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-10-14
          • 2018-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-25
          相关资源
          最近更新 更多