1

I'm writing a Stylish user style sheet, and am trying to see if something is possible. I am customizing a page that has a structure like this:

<div class="main">
    <div class="someExtraLayers">
        <div class="page">
            1
        </div>
    </div>
    <div class="someOtherLayers">
        <div class="post">
            blah blah
        </div>
        <div class="post">
            foo foo
        </div>
        <div class="post">
            bar bar
        </div>
    </div>
</div>

Where 'someExtraLayers' and 'someOtherLayers' indicate a few levels of divs inside divs. I'm not fully replicating the page's structure here for brevity's sake.

I have this in my user CSS:

div.post:nth-child(1) {
    display:block !important;
}

Essentially, I'm making visible the first post element, and this does most of what I want to do. The thing I want to add is that I only want to make that element visible if the content of the page class is 1. If it's not 1, then I don't want to display the first post element.

CSS doesn't seem to offer conditionals, or boolean ANDs, that work this way. But I'm still new-ish to CSS, so I might be missing something. If I have to use a Greasemonkey script instead, I'll do that, but I was hoping there's some CSS trickery that will let me accomplish this.

4

2 回答 2

1

Stylish 无法做到这一点,因为 Stylish 只是注入 CSS 而CSS 没有文本内容的选择器

要做你想做的事,你必须安装 Greasemonkey (Firefox) 或 Tampermonkey (Chrome),然后用户脚本可以设置该可见性。

假设 div 1包含,那么像这个完整的 GM/TM 脚本这样的东西会做你想要的。它使用了jQuery 选择器的强大功能。
您还可以在 jsFiddle 看到代码的现场演示。:

// ==UserScript==
// @name     _Show the first post on page 1
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

var pageHasOne  = $("div.main:has(div.page:contains(1))");
pageHasOne.each ( function () {
    var jThis   = $(this);  //-- this is a special var inside an .each()
    var pageDiv = jThis.find ("div.page:contains(1)");
    if ($.trim (pageDiv.text() )  == "1") {
        //--- Show the first post div. !important is not needed here.
        jThis.find ("div.post:first").css ("display", "block");
    }
} );

鉴于 jQuery javascript 必须使用的逻辑,我们可以看到 CSS 不尝试为此提供选择器的部分原因。它超出了 CSS 的任务范围,而是 javascript 的用途。


另请注意,这是针对静态页面的。如果页面对其内容使用 AJAX,则逻辑会变得更加复杂。

于 2013-11-22T01:55:10.953 回答
1

CSS 无法访问 HTML 内容。

为了解决这个问题,您还需要添加一个类以便 CSS 可以“看到”它:

HTML:

<div class="main one">
    <div class="someExtraLayers">
        <div class="page">
            1
        </div>
    </div>
    <div class="someOtherLayers">
        <div class="post">
            blah blah
        </div>
        <div class="post">
            foo foo
        </div>
        <div class="post">
            bar bar
        </div>
    </div>
</div>

CSS:

.one .post:nth-child(1) {
    display:block !important;
}
于 2013-11-21T19:16:57.910 回答