使用document迭代dom元素.getElementsByTagName,传递元素作为jquery对象



我需要的是遍历一些开始元素的dom,然后遍历开始元素以下的所有元素。

这是我到目前为止所做的。

function iterDomFromStartElem = function(startElem, callBackFunc) {
    if (startElem !== null) {
        var items = startElem.getElementsByTagName("*");
        for (var i = 0; i < items.length; i++) {
            callBackFunc(items[i]);
        }
    }
}

我需要从一些开始元素遍历dom的原因是因为我们的团队最近收到了实现字体大小调整的请求;然而,我们在许多不同的地方使用像素静态地开发了一个站点。我意识到,更简单的方法是重构现有的代码,在页面的根部设置一个静态字体大小,并在其他地方使用em/百分比,这样,如果业务所有者想要在页面上有一个调整大小的控制,我们所要做的就是在一个地方增加字体大小。这个重构将需要很多小时,而我已经用最少的人力完成了这个任务。

那么,我有一个这样定义的回调,

function resizeFont(startElem, scale) {
    iterDomFromStartElem(startElem, function(node) {
        // get current size of node, apply scale, increase font size
    }
}

使用这个原始的javascript将工作,但我有麻烦获得font-size,如果它在一个css类内声明。

我知道jquery有一个css属性如果我有一个jquery对象我可以输入$(this)。css(....)所以,

当我调用callBackFunc(项目[I]),我怎么能把项目[I]转换成一个jquery对象,以便在我的回调函数,我可以做node.css(......)?

我想我可以写$(items[I].id),也许这将是最简单的。

是否有一个更简单的方法与javascript来确定字体大小,即使该字体大小是在css类声明和css类附加到元素?

前言:我认为你最好妥善解决这个问题。抄近路也许你现在可以省一两个小时,但从长远来看,这可能会让你付出代价。

但这是你真正的问题:

我如何将项目[I]转换成一个jquery对象,以便在我的回调函数,我可以做node.css(......)?

如果你传递一个原始DOM对象到$(), jQuery将返回一个包装器。你不需要通过ID。

您还可以为所有后代元素获得一个jQuery实例,例如:

var x = $("#starting_point *");

…虽然如果循环遍历它,最终还是会创建很多临时对象,就像这样:

$("#starting_point *").each(function() {
    // Here, `this` is the raw DOM element
});

下面是一个使用jQuery循环给定起始点下的所有元素的示例,在本例中显示它们的标记和id(如果有的话)并将它们变为蓝色(live copy):

$("#start *").each(function() {
  display(this.tagName + "#" + (this.id || "?"));
  $(this).css("color", "blue");
});

注意我在下面写了。如果您还想包含#start,则选择器更改为#start, #start *

下面是一个完整的例子,增加从(和包括)给定起始点开始的元素的字体大小,其中字体大小由内联样式和样式表样式(live copy)不同地设置:

CSS:

.x13 {
  font-size: 13px;
}
.x17 {
  font-size: 17px;
}
.x20 {
  font-size: 20px;
}
HTML:

<input type="button" id="btnBigger" value="Bigger">
<div id="start" class="x13">
  This is in 13px
  <p style="font-size: 15px">This is in 15px
    <span class="x17">and this is 17px</span></p>
  <ul>
    <li id="the_list_item" style="10px">10px
      <strong style="font-size: 8px">8px
        <em class="x20">five</em>
      </strong>
    </li>
  </ul>
</div>
JavaScript:

jQuery(function($) {
  $("#btnBigger").click(function() {
    $("#start, #start *").each(function() {
      var $this = $(this),
          fontSize = parseInt($this.css("font-size"), 10);
      display("fontSize = " + fontSize);
      $this.css("font-size", (fontSize + 2) + "px");
    });
  });
  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

最新更新