每个浏览器的开发工具都会显示元素的内容、内边距、边框和边距框。有没有办法让浏览器(任何浏览器)向我显示元素的基线?这将有助于调试内联框对齐。
这并不能完全回答你的问题,但我希望它至少能有一些用处......或者它甚至会激励某人想出一个更好的!
诀窍是 a) 计算基线的位置,b) 使该信息可用于所有元素。
计算基线的方法出奇地不简单:我们必须创建两个元素,其中一个元素的字体大小为 0,然后计算它们之间顶部位置的差异。
为了将此计算放入所有 HTML 元素中,我们使用该defineProperty方法向类的原型添加一个新属性HTMLElement。
// the main functionality
Object.defineProperty(Element.prototype, 'baselinePosition',
{
get: function() {
var fs0 = document.createElement('span');
fs0.appendChild(document.createTextNode('X')); fs0.style.fontSize = '0'; fs0.style.visibility = 'hidden';
var fs1 = document.createElement('span');
fs1.appendChild(document.createTextNode('X'));
this.appendChild(fs1); this.appendChild(fs0);
var result = fs0.getBoundingClientRect().top - fs1.getBoundingClientRect().top;
this.removeChild(fs0); this.removeChild(fs1);
return result;
},
enumerable: true
});
// and a test run.
var pos = document.getElementById('test').baselinePosition;
console.log('The baseline is at ' + pos + ' px.');Run Code Online (Sandbox Code Playgroud)
<p id="test">This is the test.</p>Run Code Online (Sandbox Code Playgroud)
这里需要注意的是,您需要一个可以显示 HTML 元素节点的所有属性的浏览器。到目前为止,我发现唯一能做到这一点的是 SeaMonkey 的 DOM Inspector。
其他浏览器要么无法显示 JavaScript 节点属性,要么仅显示内置节点属性,而不显示用户添加的节点属性。
无论如何,希望这能有所帮助!
| 归档时间: |
|
| 查看次数: |
1044 次 |
| 最近记录: |