我正在将来自编辑器的 html 注入(inject)我的网站。我怎样才能像这样从子元素“继承”对齐方式:
<li>
<div align="right">one</div>
</li>
问题是元素符号是左对齐的,文本是右对齐的,我想从 div 上设置的任何内容中获取对齐方式,在这种情况下是“右”。这可能有所不同,因为它来自 html 编辑器。
CSS:
ul, ol, li {
list-style: disc !important;
}
jsfiddle:http://jsfiddle.net/bfu20zhq/
最佳答案
没有办法根据this来选择 parent 并且 MDN 没有任何迹象表明这最近发生了变化。
然而,如相关帖子中所述,这可以通过 javascript 实现(而且必须是,因为 css 还不能做到)。为此,您可以遍历 DOM 树并找到所有具有父级 li
的 div
元素,然后使它们的 align
属性相同:
// create the filter for the tree walker
var div_filter = {
acceptNode: function (node) {
if ( node.tagName == 'DIV' && node.parentElement.tagName == 'LI' ) {
return NodeFilter.FILTER_ACCEPT;
}
}
};
// create the tree walker so we can
// find all the divs
var treeWalker = document.createTreeWalker( document.body,
NodeFilter.SHOW_ELEMENT,
div_filter,
false);
// walk the DOM tree for the nodes we want
// and make the `li` elements have the same `align` as the `div`s
while (treeWalker.nextNode()) {
console.log(treeWalker.currentNode);
treeWalker.currentNode.parentElement.setAttribute('align',
/* fetch the div's align attribute */
treeWalker.currentNode.getAttribute('align') );
}
不幸的是,虽然这正确地设置了 align
属性,但它没有给出您在 this fiddle 中看到的预期结果。 . 不过,我将其保留在这里,因为我们需要它作为完整的解决方案。
在列表元素上设置 float: right
有效果,但是很糟糕。
经过一些调整,我发现将 inside
添加到 list-style
并将 text-align
调整为 right
或 left
相应地,达到预期的结果:
这就是我们想要的,如果 div
有 align = "right"
li {
list-style: disc inside;
text-align: right;
}
我们还需要将 div
更改为 display: inline-block
,这样它们就不会像非文本元素一样:
li > div {
display: inline-block;
}
如果你想让元素符号垂直对齐,你需要给div
一个明确的width
,比如width: 30%
或者类似的东西。
因此我们的 while
循环更改为:
while (treeWalker.nextNode()) {
console.log(treeWalker.currentNode);
treeWalker.currentNode.parentElement.style.textAlign =
treeWalker.currentNode.getAttribute('align');
}
这是 complete fiddle .
关于html - 匹配列表元素符号与 `<div>` 中文本的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26091617/