הערות ל-CSS ו-JS כותבים כך /* COMMENT */
הערות ל-HTML כותבים כך <!– Write your comments here –>
קודם כל בואו נראה את הקובץ mystyle.css
יש לנו צבע רקע שחור לכל HTML עמוד.
בנוסך:
- הגדרנו צבע טקסט לאלמנט-testID כצהוב.
- צבע טקסט לאלמנט-testID2 כלבן.
- רוחב של myDiv שווה ל-25% מרוחב העמוד HTML ועם קן צהוב מסביב.
בנוסף הגדרנו צבע רקע פנימי ל-myDiv – ירוק. - באדום הגדרנו צבע של הטקסט בתג p בתוך ה-myDiv.
/* Black background */ body { background-color: black; } /* yellow color for the selector #testID */ #testID { color:yellow; } /* WHITE color for the CLASS .testID2 */ .testID2 { color:white; } /* DIV */ .myDiv { width:25%; /* outset yellow-line 5px*/ border: 5px outset yellow; background-color: green; text-align: center; } /* tag p inside div will be red*/ .myDiv p { color:red; }
בקובץ HTML הגדרנו תג p:
פעם כ-id selector שזה <p id="testID">Test 1 </p>
ופעם כ-CLASS NAME שזה <p class="testID2">Test 2 </p>
בנוסף הגדרנו DIV כ-CLASS NAME שזה <div class="myDiv">
ובתוך ה-DIV הגרנו כותרת <h2> וגם טקסט עם תג <p>
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="C:\HTML-CSS-JS/mystyle.css"> <title>Java Script</title> </head> <body> <!-- Write your comments here --> <!-- Color defended by ID SELECTOR --> <p id="testID">Test 1 </p> <!-- Color defended by CLASS NAME --> <p class="testID2">Test 2 </p> <div class="myDiv"> <h2>TITLE</h2> <p>Just text in DIV...</p> </div> </body> </html>
שינוי HTML Elements בעזרת JavaScript
בדוגמה קודמת נוסיף כפתור כך שבלחיצה על הכפתור
תרוץ פוטנציה ()changeColor אשר נמצת בקובץ MyJavaScript.js
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="C:\HTML-CSS-JS/mystyle.css"> <script type="text/javascript" src="MyJavaScript.js"></script> <title>Java Script</title> </head> <body> <!-- Write your comments here --> <!-- Color defended by ID SELECTOR --> <p id="testID">Test 1 </p> <!-- Color defended by CLASS NAME --> <p class="testID2">Test 2 </p> <div class="myDiv"> <h2>TITLE</h2> <p>Just text in DIV...</p> </div> </br> <button type="button" onclick="changeColor()"> Change color!</button> </body> </html>
תג <br/> מסמל ירידת שורה, כך שהטקסט הבא יתחיל בשורה הבאה.
נגדיר פוטנציה ()changeColor בקובץ JS
ואז נשנה את הצבעים:
- דרך getElementById נשנה Test1 מצהוב לאדום
- דרך getElementsByClassName נשנה Test2 מלבן לכחול.
חשוב לציין שמכיוון שgetElementsByClassName מחזיר מערכך של כל אלמנטים
לפי תג testID2 ואנחנו צריך רק את הראשון, לכן בחרנו [document.getElementsByClassName('testID2')[0 - כנ"ל יהיה שינוי הצבע של רקע עבור myDiv לכחול.
function changeColor () {
document.getElementById('testID').style.color = 'red';
document.getElementsByClassName('testID2')[0].style.color = 'blue';
document.getElementsByClassName('myDiv')[0].style.backgroundColor = "blue";
}
תוצאה:
לפני לחיצת כפתור כפתור:
לאחר לחיצת כפתור כפתור:
כל כבוד לכם!!!
בזה נגמר הקורס מבוא לשפת JavaScript ו-HTML, אני מקווה שהקורס הזה נתן לכם רקע התחלתי בJS, HTML.