<head>
<style>
#item0{
position:absolute;
top:30;
left:40;
background-color:aliceblue;
}
#item1{
position:absolute;
top:expression(40+item0.offsetHeight);
left:40;
height:30;
text-overflow:ellipsis;
overflow:hidden;
width:expression(item0.offsetWidth);
background-color:aliceblue;
}
</style>
</head>
<body>
<div id=item0>
DOM 2 Core представляет XML-документы в виде деревьев, состоящих из узлов, которые, в свою очередь, также являются объектами и реализуют более специализированные интерфейсы. Одни типы узлов могут иметь детей, т. е. сами являться поддеревьями, другие являются листьями, т. е. детей не имеют.
</div>
<div id=item1>
После того, как обозреватель проанализировал документ и построил дерево документа, для каждого элемента дерева вычисляется значение каждого из его свойств, применимых к текущему устройству отображения. Окончательное значение свойства вычисляется в три этапа. Сначала значение определяется из спецификации (специфицированное значение), затем при необходимости преобразуется к абсолютному значению (вычисленное значение), и, наконец, преобразуется с учетом ограничений контекста (фактическое значение).
</div>
</body>
Как узнать высоту/ширину текста в пикселях?!
Код:
Во втором диве нужно найти ширину текста как с троеточием, так и без него.
А также: хотелось бы иметь возможность узнавать ширину какой-то части от всей строки
Хочется узнать, а смысл этих манипуляций? Больше проблем возникнет (из-за крайней слабой поддежкой DOM API IE-ом).
Во-первых, я часто встречался с этой проблемой и, поэтому хочется узнать более менее эффективное решение (я видел решение, использующее метод getBoundingClientRect - http://www.ageofweb.ru/blogs/users/stealthy/2005/11/4.html).
Во-вторых, сейчас я решаю следующую задачу: эмуляция Alt+Tab свитчера. Так вот, при смене размера шрифта заголовков окон меняется высота панельки, содержащей заголовок - так сделано в Windows, сл-но мне нужно сделать также. Но высота этой панельки меняется оч. хитро...
Помощь будет?
Код:
document.getElementById('item1').style.getPropertyValue('height')
Код:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML XMLNS:MSHelp = "http://msdn.microsoft.com/msHelp"><HEAD><TITLE>GetClientRects - Line rectangle collection demo</TITLE>
<META http-equiv=Content-Type content="text/html; CHARSET=iso-8859-1">
<META content=InetSDK name=AUTHOR>
<META content=EN-US name=MS.LOCALE>
<META content=noindex name=ROBOTS><LINK
href="ms-help://MS.PSDKSVR2003SP1.1033/workshop/samples/author/dhtml/refs/samplesSDKIE4.css"
type=text/css rel=stylesheet>
<SCRIPT>
window.onload=fnInit;
var rcts;
var keyCount=0;
var bIsMore=false;
var oClickClock="";
function fnHighlite(obj) {
rcts = obj.getClientRects();
rctLength= rcts.length;
if (keyCount > rctLength-1) {
idBeige.style.display="none";
keyCount = 0
}
// set the rendering properties for the yellow DIV
cdRight = rcts[keyCount].right + idBody.scrollLeft;
cdLeft = rcts[keyCount].left + idBody.scrollLeft;
cdTop = rcts[keyCount].top + idBody.scrollTop;
cdBottom = rcts[keyCount].bottom + idBody.scrollTop;
idYellow.style.top = cdTop;
idYellow.style.width = (cdRight-cdLeft) - 5;
idYellow.style.display = 'inline';
// now, set the rendering properties for the beige DIV
bndRight = obj.getBoundingClientRect().right + idBody.scrollLeft;
bndLeft = obj.getBoundingClientRect().left + idBody.scrollLeft;
bndTop = obj.getBoundingClientRect().top + idBody.scrollTop;
idBeige.style.top = bndTop;
idBeige.style.width = (bndRight-bndLeft) - 5;
idBeige.style.height = cdTop - bndTop;
if (keyCount>0){
idBeige.style.display = 'inline';
}
keyCount++;
}
// Display the length of the clientRects collection when the page loads.
function fnInit(){
oCount.innerText=oID_1.getClientRects().length
}
// Simulate clicking on the paragraph for the length of the clientRects collection.
function fnClickMore(){
if(bIsMore==false){
bIsMore=true;
oClickMore.value="Stop Clicking";
oClickClock=window.setInterval("fnSimClick()",250);
}
else{
oClickMore.value="Simulate Click";
window.clearInterval(oClickClock);
bIsMore=false;
}
}
function fnSimClick(){
if(keyCount==oID_1.getClientRects().length){
oID_1.click();
oClickMore.value="Simulate Click";
bIsMore=false;
window.clearInterval(oClickClock);
}
else{
oID_1.click();
}
}
</SCRIPT>
<LINK href="ms-help://Hx/HxRuntime/HxLink.css" type=text/css rel=stylesheet>
<STYLE type=text/css>PRE.clsCode {
FONT-SIZE: 110%
}
PRE.clsSyntax {
FONT-SIZE: 100%
}
TD DIV.clsBeta {
DISPLAY: none
}
MSHelp\:link {
CURSOR: hand; COLOR: #0000ff; TEXT-DECORATION: underline; hoverColor: #3366ff; filterString:
}
</STYLE>
<!--TOOLBAR_START--><!--TOOLBAR_EXEMPT--><!--TOOLBAR_END-->
<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
<BODY id=idBody vLink=#808080 aLink=#000000 link=#000000 bgProperties=fixed
bgColor=#ffffff leftMargin=0 topMargin=0>
<BLOCKQUOTE class=body>
<H2>getBoundingClientRects and getClientRects Sample</H2>
<P>This sample demonstrates the use of the <B>getClientRects</B> and
<B>getBoundingClientRect</B> methods. Click anywhere in the <B>Gettysburg
Address</B> to highlight the first line of text in yellow. The
<B>getClientRects</B> method is used to retrieve a collection of rectangles
and the <B>top</B>, <B>left</B>, and <B>right</B> coordinates of the line of
text to be highlighted. Using the location values, a positioned <B>DIV</B>
with a <B>zIndex</B> property set to -1 is moved into position behind the
text.</P>
<P>Additional clicks move the positioned <B>DIV</B> used for the yellow
highlight to the location of the next rectangle. A second positioned
<B>DIV</B> used for a beige highlight is moved and resized to highlight all of
the rectangles returned from the <B>getClientRects</B> method that appear
above the yellow highlight. The <B>DIV</B> used for the beige highlight is
resized based on the size of the bounding rectangle returned from the
<B>getBoundingClientRect</B> method.</P>
<P>Click the button to simulate clicking the paragraph <SPAN
id=oCount>several</SPAN> times.</P>
<P><INPUT id=oClickMore onclick=fnClickMore() type=button value="Simulate Click"></P>
<H3 align=center>Gettysburg Address</H3>
<DIV id=oID_1 onkeydown=fnHighlite(this) onclick=fnHighlite(this)>
<BLOCKQUOTE>Four score and seven years ago our fathers brought forth on this
continent a new nation, conceived in liberty and dedicated to the
proposition that all men are created equal. Now we are engaged in a great
civil war, testing whether that nation or any nation so conceived and so
dedicated can long endure. We are met on a great battlefield of that war. We
have come to dedicate a portion of that field as a final resting-place for
those who here gave their lives that that nation might live. It is
altogether fitting and proper that we should do this. But in a larger sense,
we cannot dedicate, we cannot consecrate, we cannot hallow this ground. The
brave men, living and dead, who struggled here have consecrated it far above
our poor power to add or detract. The world will little note nor long
remember what we say here, but it can never forget what they did here. It is
for us the living rather to be dedicated here to the unfinished work which
they who fought here have thus far so nobly advanced. It is rather for us to
be here dedicated to the great task remaining before us--that from these
honored dead we take increased devotion to that cause for which they gave
the last full measure of devotion--that we here highly resolve that these
dead shall not have died in vain, that this nation under God shall have a
new birth of freedom, and that government of the people, by the people, for
the people shall not perish from the earth.</BLOCKQUOTE></DIV>
<DIV id=idYellow
style="DISPLAY: none; Z-INDEX: -1; LEFT: 5px; POSITION: absolute; TOP: 400px; BACKGROUND-COLOR: yellow"></DIV>
<DIV id=idBeige
style="DISPLAY: none; Z-INDEX: -1; LEFT: 5px; POSITION: absolute; TOP: 400px; BACKGROUND-COLOR: beige"></DIV><!-- START_PAGE_FOOTER --><BR><BR><BR><MSHelp:link
tabIndex=0 keywords="msdn_copyright"
xmlns:MSHelp="http://msdn.microsoft.com/mshelp">© 2005 Microsoft Corporation.
All rights reserved.</MSHelp:link>.
<!-- END_PAGE_FOOTER --></BLOCKQUOTE></BODY></HTML>
<HTML XMLNS:MSHelp = "http://msdn.microsoft.com/msHelp"><HEAD><TITLE>GetClientRects - Line rectangle collection demo</TITLE>
<META http-equiv=Content-Type content="text/html; CHARSET=iso-8859-1">
<META content=InetSDK name=AUTHOR>
<META content=EN-US name=MS.LOCALE>
<META content=noindex name=ROBOTS><LINK
href="ms-help://MS.PSDKSVR2003SP1.1033/workshop/samples/author/dhtml/refs/samplesSDKIE4.css"
type=text/css rel=stylesheet>
<SCRIPT>
window.onload=fnInit;
var rcts;
var keyCount=0;
var bIsMore=false;
var oClickClock="";
function fnHighlite(obj) {
rcts = obj.getClientRects();
rctLength= rcts.length;
if (keyCount > rctLength-1) {
idBeige.style.display="none";
keyCount = 0
}
// set the rendering properties for the yellow DIV
cdRight = rcts[keyCount].right + idBody.scrollLeft;
cdLeft = rcts[keyCount].left + idBody.scrollLeft;
cdTop = rcts[keyCount].top + idBody.scrollTop;
cdBottom = rcts[keyCount].bottom + idBody.scrollTop;
idYellow.style.top = cdTop;
idYellow.style.width = (cdRight-cdLeft) - 5;
idYellow.style.display = 'inline';
// now, set the rendering properties for the beige DIV
bndRight = obj.getBoundingClientRect().right + idBody.scrollLeft;
bndLeft = obj.getBoundingClientRect().left + idBody.scrollLeft;
bndTop = obj.getBoundingClientRect().top + idBody.scrollTop;
idBeige.style.top = bndTop;
idBeige.style.width = (bndRight-bndLeft) - 5;
idBeige.style.height = cdTop - bndTop;
if (keyCount>0){
idBeige.style.display = 'inline';
}
keyCount++;
}
// Display the length of the clientRects collection when the page loads.
function fnInit(){
oCount.innerText=oID_1.getClientRects().length
}
// Simulate clicking on the paragraph for the length of the clientRects collection.
function fnClickMore(){
if(bIsMore==false){
bIsMore=true;
oClickMore.value="Stop Clicking";
oClickClock=window.setInterval("fnSimClick()",250);
}
else{
oClickMore.value="Simulate Click";
window.clearInterval(oClickClock);
bIsMore=false;
}
}
function fnSimClick(){
if(keyCount==oID_1.getClientRects().length){
oID_1.click();
oClickMore.value="Simulate Click";
bIsMore=false;
window.clearInterval(oClickClock);
}
else{
oID_1.click();
}
}
</SCRIPT>
<LINK href="ms-help://Hx/HxRuntime/HxLink.css" type=text/css rel=stylesheet>
<STYLE type=text/css>PRE.clsCode {
FONT-SIZE: 110%
}
PRE.clsSyntax {
FONT-SIZE: 100%
}
TD DIV.clsBeta {
DISPLAY: none
}
MSHelp\:link {
CURSOR: hand; COLOR: #0000ff; TEXT-DECORATION: underline; hoverColor: #3366ff; filterString:
}
</STYLE>
<!--TOOLBAR_START--><!--TOOLBAR_EXEMPT--><!--TOOLBAR_END-->
<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
<BODY id=idBody vLink=#808080 aLink=#000000 link=#000000 bgProperties=fixed
bgColor=#ffffff leftMargin=0 topMargin=0>
<BLOCKQUOTE class=body>
<H2>getBoundingClientRects and getClientRects Sample</H2>
<P>This sample demonstrates the use of the <B>getClientRects</B> and
<B>getBoundingClientRect</B> methods. Click anywhere in the <B>Gettysburg
Address</B> to highlight the first line of text in yellow. The
<B>getClientRects</B> method is used to retrieve a collection of rectangles
and the <B>top</B>, <B>left</B>, and <B>right</B> coordinates of the line of
text to be highlighted. Using the location values, a positioned <B>DIV</B>
with a <B>zIndex</B> property set to -1 is moved into position behind the
text.</P>
<P>Additional clicks move the positioned <B>DIV</B> used for the yellow
highlight to the location of the next rectangle. A second positioned
<B>DIV</B> used for a beige highlight is moved and resized to highlight all of
the rectangles returned from the <B>getClientRects</B> method that appear
above the yellow highlight. The <B>DIV</B> used for the beige highlight is
resized based on the size of the bounding rectangle returned from the
<B>getBoundingClientRect</B> method.</P>
<P>Click the button to simulate clicking the paragraph <SPAN
id=oCount>several</SPAN> times.</P>
<P><INPUT id=oClickMore onclick=fnClickMore() type=button value="Simulate Click"></P>
<H3 align=center>Gettysburg Address</H3>
<DIV id=oID_1 onkeydown=fnHighlite(this) onclick=fnHighlite(this)>
<BLOCKQUOTE>Four score and seven years ago our fathers brought forth on this
continent a new nation, conceived in liberty and dedicated to the
proposition that all men are created equal. Now we are engaged in a great
civil war, testing whether that nation or any nation so conceived and so
dedicated can long endure. We are met on a great battlefield of that war. We
have come to dedicate a portion of that field as a final resting-place for
those who here gave their lives that that nation might live. It is
altogether fitting and proper that we should do this. But in a larger sense,
we cannot dedicate, we cannot consecrate, we cannot hallow this ground. The
brave men, living and dead, who struggled here have consecrated it far above
our poor power to add or detract. The world will little note nor long
remember what we say here, but it can never forget what they did here. It is
for us the living rather to be dedicated here to the unfinished work which
they who fought here have thus far so nobly advanced. It is rather for us to
be here dedicated to the great task remaining before us--that from these
honored dead we take increased devotion to that cause for which they gave
the last full measure of devotion--that we here highly resolve that these
dead shall not have died in vain, that this nation under God shall have a
new birth of freedom, and that government of the people, by the people, for
the people shall not perish from the earth.</BLOCKQUOTE></DIV>
<DIV id=idYellow
style="DISPLAY: none; Z-INDEX: -1; LEFT: 5px; POSITION: absolute; TOP: 400px; BACKGROUND-COLOR: yellow"></DIV>
<DIV id=idBeige
style="DISPLAY: none; Z-INDEX: -1; LEFT: 5px; POSITION: absolute; TOP: 400px; BACKGROUND-COLOR: beige"></DIV><!-- START_PAGE_FOOTER --><BR><BR><BR><MSHelp:link
tabIndex=0 keywords="msdn_copyright"
xmlns:MSHelp="http://msdn.microsoft.com/mshelp">© 2005 Microsoft Corporation.
All rights reserved.</MSHelp:link>.
<!-- END_PAGE_FOOTER --></BLOCKQUOTE></BODY></HTML>
А как это работает?
И что ЭТО за кусок кода? Что не вижу, как он работает ;)
Сорри, исправляю...