JavaScript로 CSS 생성 콘텐츠에 액세스하는 방법
CSS counter
및 content
속성을 사용 하여 헤더와 그림의 번호 매기기를 생성합니다 .
img.figure:after {
counter-increment: figure;
content: "Fig. " counter(section) "." counter(figure);
}
이것은 (적절한 브라우저 가정) 모든 이미지 다음에 "그림 1.1", "그림 1.2"등의 멋진 레이블을 제공합니다.
질문 : Javascript에서 어떻게 액세스 할 수 있습니까? 문제는 내가 접근하고자한다는 점에서 두 가지이다 하나 (특정 DOM 노드에서) 특정 카운터의 현재 값 이나 (특정 DOM 노드에서) CSS 생성 콘텐츠의 가치 나 , 분명, 정보를 모두.
배경 : 다음과 같이 적절한 숫자를 수치화하기 위해 역 참조하는 링크에 추가하고 싶습니다.
<a href="#fig1">see here</h>
------------------------^ " (Fig 1.1)" inserted via JS
내가 볼 수있는 한,이 문제로 귀결된다 : I could access content
or counter-increment
via getComputedStyle
:
var fig_content = window.getComputedStyle(
document.getElementById('fig-a'),
':after').content;
그러나 이것은 라이브 값이 아니라 스타일 시트에 선언 된 값입니다. 실제 실시간 가치 에 액세스 할 수있는 인터페이스를 찾을 수 없습니다 . 카운터의 경우 쿼리 할 실제 CSS 속성도 없습니다.
편집 : DOM 사양을 자세히 살펴보면서 DOM 레벨 2 스타일 카운터 인터페이스를 찾았 습니다 . 이것은 a) 현재 카운터 값에 대한 액세스를 허용하고 b) 적어도 Firefox에서 구현되는 것 같습니다. 그러나 나는 그것을 사용하는 방법을 모른다. 내 현재 접근 방식은이 Firebug 출력 후 비극적으로 죽었습니다.
// should return a DOM 2 Counter interface implementation...
window.getComputedStyle(fig_a_element, ':after')
.getPropertyCSSValue("counter-increment")[0]
.getCounterValue();
[Exception... "Modifications are not allowed for this document" code: "7"
nsresult: "0x80530007 (NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR)"
location: "http://localhost/countertest.html Line: 71"]
이것이 어떻게 실현 될 수 있는지 어떤 아이디어라도 높이 평가 될 것입니다.
편집 2 : 분명히 DOM 레벨 2 스타일의 카운터 객체를 잘못 해석했습니다. 또한 현재 카운터 값을 반환하는 속성이 없습니다. 이로 인해 위의 접근 방식이 무효화됩니다.
새로운 접근 방식 : DOM을 통해 의사 요소의 내용을 읽을 수 있습니까? 즉, 의사 요소를 treeWalker
선택한 다음 (생각할 수 있음) nodeValue
? ( 지금 'jQuery' 를 입력하기 시작하면 해당 용어를 'Sizzle' 로 변경하는 것을 재고하십시오 ...)
실제 실시간 가치에 액세스 할 수있는 인터페이스를 찾을 수 없습니다. [카운터]
네. 나는 하나가 없다고 생각합니다. 죄송합니다.
내가 생각할 수있는 유일한 것은 문서의 요소 이전에 모든 요소 ( :before
/ :after
의사 요소 포함)를 살펴보고 카운터를 찾고 거기에 몇 개가 있는지 추가하는 것입니다.
분명히 그것은 끔찍합니다. 브라우저의 자체 counter
메커니즘 을 재현하려고 한다면 스크립트 기반 카운터로 대체하는 것이 더 쉬울 것입니다 (IE <= 7의 카운터 / 컨텐츠 지원이 부족한 경우 훨씬 더 호환 가능). 예. 라인을 따라 뭔가 :
<a href="#prettypicture">this</a>
<div class="counter level=0">...</div>
<img id="prettypicture" class="counter level=1" alt="ooo, pretty"/>
window.onload= function() {
var counters= Node_getElementsByClassName(document.body, 'counter');
var indices= [];
for (var counteri= 0; counteri<counters.length; counteri++) {
var counter= counters[counteri];
var level= Element_getClassArgument(counter, 'level');
while (indices.length<=level)
indices.push(0);
indices[level]++;
indices= indices.slice(level+1);
var text= document.createTextNode('Figure '+indices.join('.'));
counter.parentNode.insertBefore(text, counter.nextSibling);
if (counter.id!=='') {
for (var linki= document.links.length; linki-->0;) {
var link= document.links[i];
if (
link.hostname===location.hostname && link.pathname===location.pathname &&
link.search===location.search && link.hash==='#'+counter.id
) {
var text= document.createTextNode('('+indices.join('.')+')');
link.parentNode.insertBefore(text, link.nextSibling);
}
}
}
}
};
이것을 읽으십시오 :
생성 된 콘텐츠는 문서 트리를 변경하지 않습니다. 특히 문서 언어 프로세서 (예 : 재분석)로 피드백되지 않습니다.
Content specified in a stylesheet does not become part of the DOM.
so for this reason the getComputedStyle will not work in this case; i think the only way, is to perform a classic loop through as someone has described below!
I would port your css to Javascript, this enables you to get the figure caption and also you get greater browser coverage. Using jQuery you'd do something like this:
$(function() {
var section = 0;
$(".section").each(function() {
section++;
var figure = 0;
$(this).find("img.figure").each(function() {
figure++;
var s = "Fig. " + section + "." + figure;
$(this).attr({alt:s}).after(s);
});
});
});
Then you could do:
<div class="section">blabla <img id="foo" src="http://www.example.com/foo.jpg"></div>
<p>Lorem ipsum dolor sit amet <a href="#foo" class="figurereference">see here</a></p>
<script type="text/javascript">
$(function() {
$("a.figurereference").each(function() {
var selector = $(this).attr("href");
var $img = $(selector);
var s = $(this).text() + " (" + $img.attr("alt") + ")";
$(this).text(s);
});
});
</script>
Though I agree that doing this using CSS would be very neat.
I cannot find any interface to access the real live value.
If you can't get the value from window.getComputedStyle
, it seems that it would be impossible.
More importantly, while it can do it, I think this might be abusing CSS since you're breaking the barrier between content and presentation at this point.
Check out this related question What are good uses of css “Content” property?
ReferenceURL : https://stackoverflow.com/questions/2651739/how-to-access-css-generated-content-with-javascript
'programing' 카테고리의 다른 글
Symfony2 느린 초기화 시간 (0) | 2021.01.17 |
---|---|
.m2 폴더 또는 settings.xml의 대체 위치를 영구적으로 지정하는 방법은 무엇입니까? (0) | 2021.01.17 |
반복되는 fmap으로 재미 (0) | 2021.01.16 |
C ++에서 set과 unordered_set의 차이점은 무엇입니까? (0) | 2021.01.16 |
C99에서 f () + g ()는 정의되지 않았습니까 아니면 단순히 지정되지 않았습니까? (0) | 2021.01.16 |