sbi*_*nko 19 html javascript css jquery
使用jQuery检查元素是否在正常流程中的最优雅方法是什么?
根据CSS3规范,
如果符合以下情况,则框属于流程:
其"显示"的使用值为"块","列表项","表格"或模板.
其'float'的使用值为'none'.
其"位置"的使用价值是"静态"或"相对".
它既可以是流根的子节点,也可以是属于流的子节点.
我应该检查所有这些条件,还是有更好的方法?
我认为另一个“流动”要求是overflow设置为visible.
\n\n\n\n\n浮动、绝对定位的元素、不是块框的块容器(例如行内块、表格单元格和表格标题)以及具有“溢出”而不是“可见”的块框(除非值已传播到视口)为其内容建立新的块格式化上下文。
\n
根据您引用的要求和overflow要求,这是使用 jquery 的一种方法:
function isInFlow(elm, ctxRoot) {\n\n ctxRoot = ctxRoot || document.body;\n\n var $elm = $(elm),\n ch = -1,\n h;\n\n if (!$elm.length) {\n return false;\n }\n\n while ($elm[0] !== document.body) {\n h = $elm.height();\n if (h < ch || !okProps($elm)) {\n return false;\n }\n ch = h;\n $elm = $elm.parent();\n\n if (!$elm.length) {\n // not attached to the DOM\n return false;\n }\n if ($elm[0] === ctxRoot) {\n // encountered the ctxRoot and has been\n // inflow the whole time\n return true;\n }\n }\n // should only get here if elm\n // is not a child of ctxRoot\n return false;\n}\n\nfunction okProps($elm) {\n\n if ($elm.css(\'float\') !== \'none\'){\n return false; \n }\n if ($elm.css(\'overflow\') !== \'visible\'){\n return false; \n }\n switch ($elm.css(\'position\')) {\n case \'static\':\n case \'relative\':\n break;\n default:\n return false;\n }\n switch ($elm.css(\'display\')) {\n case \'block\':\n case \'list-item\':\n case \'table\':\n return true;\n }\n return false;\n}\n\xe2\x80\x8b \nRun Code Online (Sandbox Code Playgroud)\n\n有关测试用例,请参阅此jsFiddle 。
\n\n我不确定使用window.getComputedStyle()或不使用是否会更好。
该函数正在检查是否elm在ctxRoot\ 的流或块格式化上下文中(我认为它以前被称为)。如果ctxRoot未提供,它将检查该body元素。这不会检查以确保ctxRoot其处于流动状态。所以,使用这个 HTML
<div id="b" style="overflow: hidden;">\n <div id="ba">ba\n <p id="baa">baa</p>\n <span id="bab">bab</span>\n <span id="bac" style="display:block;">bac</span>\n </div>\n</div>\nRun Code Online (Sandbox Code Playgroud)\n\n测试用例是:
\n\nvar b = $(\'#b\')[0];\nconsole.log(\'no \',isInFlow(b));\nconsole.log(\'no \',isInFlow(\'#ba\'));\nconsole.log(\'yes \',isInFlow(\'#ba\', b));\nconsole.log(\'no \',isInFlow(\'#baa\'));\nconsole.log(\'yes \',isInFlow(\'#baa\', b));\nconsole.log(\'no \',isInFlow(\'#bab\'));\nconsole.log(\'no \',isInFlow(\'#bab\', b));\nconsole.log(\'no \',isInFlow(\'#bac\'));\nconsole.log(\'yes \',isInFlow(\'#bac\', b));\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1523 次 |
| 最近记录: |