找到元素相对于视口或文档的整数像素位置:getBoundingClientRect?

时间:2015-06-18 07:55:45

标签: javascript html css

函数getBoundingClientRect()可以返回非整数值。例如,像:

CREATE PROCEDURE UpdateTheiftFundInterest   
AS 
DECLARE @var1 VARCHAR(50), @var3 CURSOR, @var4 INT
SET @var1 = 0;
SET @var3 = CURSOR FOR
SELECT EmNo FROM [WBSEB].[dbo].[PersonalLedgerForTFundAndShareClone]
OPEN @var3
FETCH NEXT
FROM @var3 INTO @var1
WHILE @@FETCH_STATUS = 0
BEGIN
SET @var4 = 0;

SELECT @var4=SUM(TInterest)
FROM [WBSEB].[dbo].[PersonalLedgerForTFundAndShareClone]
WHERE TDate >= '2014-03-31 00:00:00.000' AND TDate <= '2015-03-31 00:00:00.000' 
AND EmNo = @var1

UPDATE [WBSEB].[dbo].[PersonalLedgerForTFundAndShareClone]
SET TInterest = @var4
Where TDate = '2015-03-31 00:00:00.000' AND EmNo = @var1

FETCH NEXT
FROM @var3 INTO @var1
END

CLOSE @var3
DEALLOCATE @var3
GO

<div style="position: relative; left: 5%; width: 66.666%"></div> 的{​​{1}}和left值几乎总是具有非整数值。您可以在http://plnkr.co/edit/QW91gy3hPMagSECQswdM?p=preview看到此信息,其左侧值的示例值为32.796875(至少在Chrome中)。

如何在屏幕上实际渲染这些非整数值,我认为是browser-dependent

那么,我如何以编程方式在屏幕上找到元素的整个像素坐标?

编辑:理想情况下不使用jQuery,理想情况下不使用DOM。

1 个答案:

答案 0 :(得分:1)

许多现代浏览器使用子像素渲染,因此很可能不存在全像素坐标。

但是使用jQuery,您可以执行类似这样的操作,以获得相对于文档空间的数组[left,top,width,height]:

function bounds(el) {

    var $el = $(el);
    if (!$el.is(':visible')) {
        return null;
    }

    var offset = $el.offset();
    return [offset.left, offset.top, $el.outerWidth(), $el.outerHeight()];
}

相对于Viewport:

function boundsVp(el) {

    var $el = $(el);
    if (!$el.is(':visible')) {
        return null;
    }

    var $win = $(window);
    var offset = $el.offset();
    return [offset.left - $win.scrollLeft(), offset.top - $win.scrollTop(), $el.outerWidth(), $el.outerHeight()];
}

你可能也对jQuery.fracs感兴趣..