CSS에서 자바 스크립트 사용
CSS 내에서 Javascript를 사용할 수 있습니까?
그렇다면 간단한 예를들 수 있습니까?
IE와 Firefox에는 모두 CSS에서 JavaScript를 실행하는 방법이 있습니다. Paolo가 언급했듯이 IE의 한 가지 방법은 expression
기술이지만 스크립트를 포함하는 별도의 XML이 CSS를 통해로드되는 더 모호한 HTC 동작도 있습니다. XBL을 사용하는 Firefox 용 유사한 기술이 있습니다 . 이러한 기술은 CSS에서 JavaScript를 직접 제외하지 않지만 효과는 동일합니다.
IE와 HTC
다음과 같은 CSS 규칙을 사용하십시오.
body {
behavior:url(script.htc);
}
해당 script.htc 파일에는 다음과 같은 내용이 있습니다.
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
HTC 파일은 main()
이벤트 에서 함수를 실행합니다 ondocumentready
(HTC 문서의 준비 상태 참조).
Firefox와 XBL
Firefox는 XBL을 사용하여 유사한 XML 스크립트 실행 해킹을 지원합니다.
다음과 같은 CSS 규칙을 사용하십시오.
body {
-moz-binding: url(script.xml#mycode);
}
그리고 script.xml 내에서 :
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
생성자 태그 내의 모든 코드가 실행됩니다 (CDATA 섹션에 코드를 래핑하는 것이 좋습니다).
두 기술 모두 CSS 선택자가 문서 내의 요소와 일치하지 않는 한 코드가 실행되지 않습니다 . 와 같은 것을 사용 body
하면 페이지로드시 즉시 실행됩니다.
난 당신이 생각 할 수있다 어떤 생각 expressions
이나 "동적 속성" 오직 IE에서 지원하고 자바 스크립트 식의 결과에 속성을 설정할 수 있습니다. 예:
width:expression(document.body.clientWidth > 800? "800px": "auto" );
이 코드는 IE max-width
가 지원하지 않는 속성을 에뮬레이트합니다 .
그러나 고려되는 모든 사항은 이러한 . 그들은 나쁘고 나쁜 것입니다.
제공 한 정보를 바탕으로 잠재적으로 문제를 해결할 수 있도록 동적 CSS를 찾고 있다고 가정하겠습니다. 이 경우 서버 측 스크립팅 언어를 사용하여 수행 할 수 있습니다. 예를 들어 (그리고 저는 이와 같은 일을 절대적으로 좋아합니다) :
styles.css.php :
body
{
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
}
이것은 배경 이미지를 $ user_country 변수 에 저장된 것으로 설정합니다 . 이것은 동적 CSS의 한 예일뿐입니다. CSS와 서버 측 코드를 결합 할 때 사실상 무한한 가능성이 있습니다. 또 다른 경우는 사용자가 사용자 정의 테마를 만들고 데이터베이스에 저장 한 다음 PHP를 사용하여 다양한 속성을 설정하는 것과 같은 작업을 수행하는 것입니다.
user_theme.css.php :
body
{
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
}
#panel
{
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
}
Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.
IE supports CSS expressions:
width:expression(document.body.clientWidth > 955 ? "955px": "100%" );
but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.
I ran into a similar problem and have developed two standalone tools to accomplish this:
CjsSS.js is a Vanilla Javascript tool (so no external dependencies) that supports back to IE6.
ngCss is an Angular Module+Filter+Factory (aka: plugin) that supports Angular 1.2+ (so back to IE8)
Both of these tool sets allow you to do this in a STYLE tag or within an external *.css file:
/*<script src='some.js'></script>
<script>
var mainColor = "#cccccc";
</script>*/
BODY {
color: /*{{mainColor}}*/;
}
And this in your on-page style
attributes:
<div style="color: {{mainColor}}" cjsss="#sourceCSS">blah</div>
or
<div style="color: {{mainColor}}" ng-css="sourceCSS">blah</div>
NOTE: In ngCss, you could also do $scope.mainColor
in place of var mainColor
By default, the Javascript is executed in a sandboxed IFRAME, but since you author your own CSS and host it on your own server (just like your *.js files) then XSS isn't an issue. But the sandbox provides that much more security and peace of mind.
CjsSS.js and ngCss fall somewhere in-between the other tools around to accomplish similar tasks:
LESS, SASS and Stylus are all Preprocessors only and require you to learn a new language and mangle your CSS. Basically they extended CSS with new language features. All are also limited to plugins developed for each platform while CjsSS.js and ngCss both allow you to include any Javascript library via
<script src='blah.js'></script>
straight in your CSS!AbsurdJS saw the same problems and went the exact opposite direction of the Preprocessors above; rather than extending CSS, AbsurdJS created a Javascript library to generate CSS.
CjsSS.js and ngCss took the middle ground; you already know CSS, you already know Javascript, so just let them work together in a simple, intuitive way.
Not in any conventional sense of the phrase "inside CSS."
This turns out to be a very interesting question. With over a hundred properties being set, you'd think that you'd be allowed to type .clickable { onclick : "alert('hi!');" ; } in your CSS, and it'd work. It's intuitive, it makes so much sense. This would be amazingly useful in monkey-patching dynamically-generated massive UIs.
The problem:
The CSS police, in their infinite wisdom, have drawn a Chinese wall between presentation and behavior. Any HTML properly labeled on-whatever is intentionally not supported by CSS. (Full Properties Table)
The best way around this is to use jQuery, which sets up an interpreted engine in the background to execute what you were trying to do with the CSS anyway. See this page: Add Javascript Onclick To .css File.
Good luck.
참고URL : https://stackoverflow.com/questions/476276/using-javascript-in-css
'Program Tip' 카테고리의 다른 글
Git 숨김 메시지 변경 (0) | 2020.11.08 |
---|---|
Spring Websocket에서 특정 사용자에게 메시지 보내기 (0) | 2020.11.08 |
git rebase and git push : non-fast forward, why use? (0) | 2020.11.08 |
단일 책임 원칙과 우려 사항 분리의 차이점 (0) | 2020.11.08 |
일시적으로 사용할 수없는 페이지에 대한 HTTP 상태 코드 (0) | 2020.11.08 |