【问题标题】:Javascript/Tumblr: add CSS class on condition (has to be JS because Tumblr)Javascript/Tumblr:按条件添加 CSS 类(必须是 JS,因为 Tumblr)
【发布时间】:2012-10-27 22:24:29
【问题描述】:

很抱歉,经过几个小时的尝试,我只需要请教专家 :)

我的 Tumblr 主题中有以下代码:

   {block:Photo}
   <li class="post photo"> 
   // Retrieving photo url here using {PhotoURL-500}.
   {/block:Photo}

这会检索所有照片帖子并将它们显示在页面上。

现在我想给 li 一个类,这取决于图像方向。我已通过以下方式检索到:

<script type="text/javascript">

var width = {PhotoWidth-500}; // this is a Tumblr variable that gets the width
var height = {PhotoHeight-500}; // this is a Tumblr variable that gets the height

if (width > height) {
// Here I get stuck, I want to append class="horizontal" to the li above.
}
else {
// append class="vertical"
}
</script>

我确实必须调用 {block:Photo} 中的 javascript,否则我无法确定每张照片的单独高度和宽度。作为提醒;我很想在 PHP 中执行此操作并只是回显它,但 Tumblr 不允许这样做。而且我是个JS菜鸟……

我们将不胜感激!提前致谢!

【问题讨论】:

    标签: javascript image orientation tumblr


    【解决方案1】:

    在任何modern browser 上,您可以使用querySelectorAll 来获取与选择器匹配的元素的NodeList,例如

    var list = querySelectorAll(".post.photo");
    

    ...然后循环遍历它们附加到它们的className 属性。例如:

    var list = querySelectorAll(".post.photo"),
        index,
        node;
    
    for (index = 0; index < list.length; ++index) {
        node = list[index];
        if (some_condition) {
            node.className += " theNewClassToAdd";
        }
    }
    

    如果您需要支持旧版浏览器,getElementsByClassName 已经存在了很长时间(但我相信它只支持单个类的查询,因此您必须进行后处理以确保两个类都存在) .

    或者为了获得最广泛的支持,通过使用像 jQueryYUIClosureany of several others 这样的体面的库来利用其他人的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多