戻る

JavaScriptでCSSプロパティを取得する

JavaScriptでCSSプロパティを取得する

イベントハンドラ(body要素に記述)

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function getCss(){
	window.alert(document.defaultView.getComputedStyle(document.getElementsByTagName("p")[0], null).color);
	
	//下の記述では取得できない
	//window.alert(document.getElementsByTagName("p").style.color)
}
</script>
</head>
<body>
	<p>テキストテキストテキストテキストテキスト</p>
	<input type="button" value="click" onclick="getCss();">
</body>
</html>

イベントハンドラ(scriptタグ内に記述)

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.onload = function(){
	window.document.getElementsByTagName("input")[0].onclick = function(){
		window.alert(document.defaultView.getComputedStyle(document.getElementsByTagName("p")[0], null).color);
		
		//下の記述では取得できない
		//window.alert(document.getElementsByTagName("p").style.color)
	}
}
</script>
</head>
<body>
	<p>テキストテキストテキストテキストテキスト</p>
	<input type="button" value="click">
</body>
</html>

イベントリスナ

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.addEventListener("load",function(){
	window.document.getElementsByTagName("input")[0].addEventListener("click",function(){
		window.alert(document.defaultView.getComputedStyle(document.getElementsByTagName("p")[0], null).color);
		
		//下の記述では取得できない
		//window.alert(document.getElementsByTagName("p").style.color)
	});
});
</script>
</head>
<body>
	<p>テキストテキストテキストテキストテキスト</p>
	<input type="button" value="click">
</body>
</html>

jQueryのcss関数

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
	$("input").click(function(){
		window.alert($("p").css("color"));
	});
});
</script>
</head>
<body>
	<p>テキストテキストテキストテキストテキスト</p>
	<input type="button" value="click">
</body>
</html>

inserted by FC2 system