I have begun to write it out and I used the same size (100px by 100px) as I used in a previous question. I'm trying to use only Javascript for now although I plan on using jQuery some time in the future. The main problem I see now is that on the line ( this.style.width
) 'this' is not yet defined so the code does not know that 'this' refers to the div and I am unsure how this would be done using an event listener rather than childNodes
(which I know how to do).
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<style>
div {background-color: #999999;width: 100px;height: 100px;}
</style>
<title></title>
</head>
<body>
<div id="myDiv" onClick="handleClick(event)"></div>
<script src="js/main.js"></script>
</body>
</html>
/**
* Created by Mark M.G on 4/1/2015.
* n221
*/
function handleClick(event){
this.style.width = ( parseInt( this.style.width ) *1.2 ) + 'px';
this.style.height = ( parseInt( this.style.height ) *1.2 ) + 'px';
}
Try to use this
instead of event
in your onClick
event, and use a different parameter name in the event handler like ' element
' to avoid confusion. :) Then replace this
in the event handler with the parameter name (' element
') to access the clicked element in the event handler.
This is a pure JS working solution based on your code: http://jsfiddle.net/oco94wrs/1/
HTML:
<div id="myDiv"></div>
CSS:
div {background-color: #999999;width: 100px;height: 100px;}
Javascript:
var div = document.getElementById('myDiv');
div.addEventListener('click', function (event) {
this.style.width = ( parseInt( this.offsetWidth ) *1.2 ) + 'px';
this.style.height = ( parseInt( this.offsetHeight ) *1.2 ) + 'px';
});
Now, the this
is referring to the actual div because I assigned the click event listener directly to the div. On your code, the this
was referring to the window object because it was in a global function.
Another possible solution could be to use event.target.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.