Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1 MB
Nội dung
14.2 Applying a Different Stylesheet Based on the Time of Day
Problem
You want to apply a different stylesheet as the day progresses.
Solution
Pull in the time on the user’s clock and deliver the appropriate stylesheet:
<script type="text/javascript">
function setTimedStylesheet() {
var theTime = new Date().getHours();
if (8 <= theTime&&theTime < 20) {
document.write("<link rel='stylesheet' href='daytime.css'
type='text/css'>");
}
if (20 <= theTime&&theTime < 8) {
document.write("<link rel='stylesheet' href='nighttime.css'
type='text/css'>");
}
}
setTimedStylesheet();
</script>
Make
sure you include the noscript element that includes a link to the default stylesheet
in case the browser does not have JavaScript:
<script type="text/javascript">
function setTimedStylesheet() {
var theTime = new Date().getHours();
if (8 <= theTime&&theTime < 20) {
document.write("<link rel='stylesheet' href='daytime.css'
type='text/css'>");
}
if (20 <= theTime&&theTime < 8) {
document.write("<link rel='stylesheet' href='nighttime.css'
type='text/css'>");
}
}
setTimedStylesheet();
</script>
<noscript>
<link href="default.css" rel="stylesheet" type="text/css">
</noscript>
Discussion
Creating a customized look and feel based on the time of day isn’t a far-fetched notion.
Radio and television stations in the United States divide their broadcasts based on the
time of day—for example, Daytime Emmy Awards, drive-time radio shows, prime time
television shows, and so on.
14.2 Applying a Different Stylesheet Based on the Time of Day | 625
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The main problem with using this method is that you are assuming the clocks on peo-
ple’s computers are actually accurate.
Another solution is to get the time of day from your server through a middleware pro-
gramming language such as PHP and pass it on as a variable to the JavaScript.
See Also
The Date object reference at http://www.w3schools.com/jsref/jsref_obj_date.asp
14.3 Redirecting to a Mobile Site Based on the Browser’s
Screen Width
Problem
You want to apply a change to the stylesheet based on the browser’s screen width.
Solution
Detect the screen width of the current browser and redirect the browser to a more
mobile-friendly version of the site’s design:
<script type= "text/javascript">
if (screen.width <= 481) {
document.location = "http://mobi.example.com/"
}
</script>
Discussion
The base resolution relies on the JavaScript being able to detect the browser width
(based in pixels). If the browser width is less than or equal to 481 pixels, it’s assumed
that the browser is a mobile device.
Not all mobile devices have JavaScript.
Higher-resolution design
You
can also flip the script to detect whether a user’s browser has a larger-than-average
browser window open:
<script type= "text/javascript">
if (screen.width <= 481) {
document.location = "http://mobi.example.com/"
} else if (screen.width >= 1280) {
626 | Chapter 14: Interacting with JavaScript
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
document.location = "http://high-def.example.com/";
}
</script>
See Also
More
robust JavaScript for delivering a resolution-independent layout at http://www
.themaninblue.com/writing/perspective/2004/09/21/
14.4 Adding a JavaScript Framework to a Web Page
Problem
You want to add a JavaScript framework to a web page, as shown in Figure 14-2.
Figure 14-2. The jQuery framework home page
Solution
Use
Google’s hosting feature to associate the jQuery framework (see Figure 14-3, shown
later) to a web page:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
14.4 Adding a JavaScript Framework to a Web Page | 627
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Then, below the citing of the jQuery framework, add a custom script:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
// Your code goes here
$(document).ready(function(){
window.alert("Hello, world! You have JavaScript!")
});
</script>
Discussion
By
using Google to host the jQuery framework code, you reap three immediate benefits.
The first benefit is that of caching. If other websites utilize Google’s services and link
to jQuery, the code is cached within the browser. When a site visitor goes to another
site, the page renders faster since the jQuery is already cached. Even with the minified
and gzipped version weighing 19 KB, this translates to savings for your users.
A second benefit deals with how many connections a browser can make to a web server.
To not overwhelm a server, a browser limits the number of connections made to a web
server as it downloads the HTML, imagery, scripts, and so on. Offloading the jQuery
framework to another server makes the page render faster.
The third benefit is that Google’s servers are likely to be faster at delivering files such
as the jQuery framework to the site visitor’s machine, unless your server was possibly
a stone’s throw from your site visitors.
The alert statement is included as a simple demonstration of where cus-
tom
JavaScript is placed. If a simple alert statement were all that was
needed, the script would be a quick line of code bypassing the need for
a JavaScript framework:
<script type="text/javascript">
window.alert("Hello, world! You have JavaScript!")
</script>
See Also
The list of jQuery and other Ajax libraries hosted by Google at http://code.google.com/
apis/ajaxlibs/documentation/
14.5 Using CSS3 Selectors in IE6 and IE7
Problem
You want to use CSS3 selectors in earlier versions of Internet Explorer.
628 | Chapter 14: Interacting with JavaScript
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Solution
First, include CSS3 syntax within the stylesheet for CSS3-capable browsers:
#content {
border: 4px solid black;
}
#content p {
margin: 1em 0;
}
/* removes the bottom margin from the last paragraph */
#content p:last-child {
margin: 1em 0 0 0;
}
Then
use jQuery’s ability to reference portions of a document through standardized
CSS3 syntax:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
// Your code goes here
$(document).ready(function(){
$("#content p:last-child").css("margin","1em 0 0 0");
});
</script>
Discussion
One of the benefits of using a JavaScript framework such as jQuery is its usage of CSS
selectors. Instead of styles being applied to a page, selectors associate functions and
behaviors to parts of the page.
To use a CSS selector, first use what’s called a jQuery object:
$(css-selector);
Then set a CSS selector within the jQuery object:
$("p+p");
Next, add the CSS declaration:
$("p+p").css("font-weight","normal");
jQuery might not understand some CSS shorthand properties. If jQuery
is
not affecting the look of the page as intended through a CSS shorthand
property, use the CSS properties that make up the shorthand properties
instead. For example, use border-right instead of simply border.
14.5 Using CSS3 Selectors in IE6 and IE7 | 629
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Hiding extraneous JavaScript from modern browsers
Although jQuery is a solution for fixing older versions of Internet Explorer, modern
browsers already support the CSS rule. So, reapplying the same effect in a web page is
a little overkill.
To reduce browser load, use conditional comments (see Recipe 12.7) to let previous
versions of Internet Explorer see the JavaScript:
<! [if lt IE 8]>
<script type="text/javascript">
// Your code goes here
$(document).ready(function(){
$("#content p:last-child").css("margin","1em 0 0 0");
});
</script>
<![endif] >
Dean Edwards’s IE7 script
Dean Edwards’s IE7 script (see http://code.google.com/p/ie7-js/) attempts to fix a lot of
the issues with previous versions of IE through JavaScript.
By attaching some JavaScript to your page, you can fix a good number of bugs that
afflict these browsers. However, the IE7 fix is specific to only the issues with these
browsers, and the file size is not trivial. With a file size of 71.1 KB, you have to weigh
whether using a large file to fix older browsers for your visitors is worthwhile.
Also, the script is in beta, and its last update occurred in February 2008. Although Dean
Edwards’s script does a great job of fixing a lot of issues with IE6, some issues might
crop up if you push the edges of trying to get IE6 to behave like a modern browser.
A number of the current-day JavaScript frameworks owe much to Dean
Edwards’s code.
See Also
The css function page at http://docs.jquery.com/API/1.3/CSS
14.6 Zebra-Striping an HTML Table with JavaScript
Problem
You
want to apply background colors to every other HTML table row without manually
adding class selectors.
630 | Chapter 14: Interacting with JavaScript
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Solution
Use jQuery’s ability to add and remove class attributes to HTML elements.
First, create CSS rules for alternating colors:
table.striping tr.diff td {
background-color: #cbc1be;
}
Then write code for jQuery in which alternating rows are selected:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".striping tr:even").addClass("diff");
});
</script>
With
the table row selected, add a class attribute with a value of diff to each row to
apply the alternating background colors, as shown in Figure 14-3:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".striping tr:even").addClass("diff");
});
</script>
Figure 14-3. Alternating striping of table rows
Discussion
Unlike Recipe 14.3, where the Solution relied on hardcoding the CSS rule in the Java-
Script,
the CSS rule here is prewritten. Then the JavaScript goes through the work of
automatically applying the class attribute to every other row.
14.6 Zebra-Striping an HTML Table with JavaScript | 631
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using a pure CSS solution
The CSS-only solution for this recipe is to use :nth-child (see Recipe 9.8):
tr:nth-child(even) td {
background-color: #cbc1be;
}
You can use conditional comments to hide the JavaScript (as shown in the Discussion
in Recipe 12.3) in tandem with the jQuery solution.
See Also
The addClass jQuery attribute page at http://docs.jquery.com/Addclass
14.7 Highlighting a Table Row with Mouseovers
Problem
You want to provide a method for highlighting a table row, even in Internet Explorer 6.
Solution
Create a CSS rule with a class selector for the background color of the highlighted table
row:
table.striping tr.over td {
background-color: #fbc057;
}
Then use the jQuery object to pinpoint where the class selector should be applied:
$(".striping tr");
Instruct jQuery to activate only when the user hovers her mouse over a link:
$(".striping tr").mouseover();
Next, start a function:
$(".striping tr").mouseover(function() {
});
Let the jQuery know that the function applies to what is currently selected (which are
the table rows):
$(".striping tr").mouseover(function() {
$(this);
});
Use the addClass() function to insert the over class attribute into the table row:
$(".striping tr").mouseover(function() {
$(this).addClass("over");
});
632 | Chapter 14: Interacting with JavaScript
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Now when a user rolls her mouse cursor over the table rows, the rows become high-
lighted. However, the Solution so far only inserts the class attribute and does not re-
move it when the user rolls her mouse cursor off the table row, as shown in Figure 14-4.
Figure 14-4. Table rows changing background color
Use
the removeClass() function to take away the class attribute, as shown in Figure 14-5:
$(".striping tr").mouseover(function() {
$(this).addClass("over");
});
$(".striping tr").mouseout(function() {
$(this).removeClass("over");
});
Figure 14-5. Table row colors reverting when mouse cursor moves off the table row
Discussion
This
Solution introduces two helpful events for creating interesting effects within a web
page: mouseover() and mouseout(). Both are popular regular JavaScript functions that
have been used to achieve image-based rollovers before the popularity of CSS-only
image-based rollovers.
14.7 Highlighting a Table Row with Mouseovers | 633
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chaining functions
With the jQuery events tied to the same elements of a web page, the table rows, it’s
possible to reduce the code through a process called chaining. This technique removes
the duplicate jQuery object like so:
$(".striping tr").mouseover(function() {
$(this).addClass("over");
}).mouseout(function() {
$(this).removeClass("over");
});
See Also
The removeClass jQuery page at http://docs.jquery.com/Attributes/removeClass
14.8 Adding Effects to Simple Image Rollovers
Problem
You want to add fades to rollovers within a web page.
Solution
Set up a jQuery object with a mouseover function (as shown in Figure 14-6):
$("#site-nav a").mouseover(function () {
});
Then use the fadeTo() function to set the opacity to 50%:
$("#site-nav a").mouseover(function() {
$(this).fadeTo("slow", .50);
});
Figure 14-6. Rolling over the images to create a fade effect
Now
add an additional mouseout function when the user rolls off the navigation to
return the opacity to 100%, as shown in Figure 14-7:
$("#site-nav a").mouseover(function () {
$(this).fadeTo("slow", .50);
}).mouseout(function () {
$ (this).fadeTo("slow", 1);
});
634 | Chapter 14: Interacting with JavaScript
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... tools, and read current CSS news CSS 2.1 specification (http://www.w3.org/TR /CSS2 1/) Browser implementations of the CSS specification are sometimes a confusing mess When tracking down how to achieve a certain look or an implementation bug, check the specification (as well as the CSS support charts) CSS3 specification (http://www.w3.org/Style /CSS/ current-work) The forthcoming CSS3 specification is still... HTML5 and CSS3 standards at a rapid pace, dealing with uneven support of CSS3 and HTML5 across modern browsers becomes an issue Web designers Faruk Ateş and Paul Irish created this simple JavaScript library that allows for basic cross-browser development As of this writing, Modernizr checks for the following HTML5 and CSS3 features: • • • • • • • opacity: CSS animations CSS columns CSS gradients CSS reflections... venue for discussing the theories and future of CSS Questions about the specification or about CSS proposals are welcomed; however, discussions regarding practical applications of the technology are discouraged References CSS Browser Support charts (http://westciv.com/wiki /CSS_ Compatibility_Guide/) If you run into problems developing with CSS, check the CSS support charts to determine whether there is... (http://www.w3.org/QA/2002/04/valid-dtd-list.html) Assigning the right DOCTYPE to a web page helps to establish the correct manner in which browsers will render your web page and validators will check your code On this web page is a listing of the most commonly used DOCTYPEs W3C’s CSS home page (http://www.w3.org/Style /CSS/ ) This is the official site for CSS At this site you can learn about the history of CSS, investigate resources and authoring... (http://www.meyerweb.com/eric /css/ edge/) Eric A Meyer’s workshop displays some of his more advanced CSS experiments CSS Zen Garden (http://www.csszengarden.com/) CSS Zen Garden showcases how web developers from all over the world restyle the same content Surfing through several designs is great inspiration, but it’s also a fantastic way to better understand the concept of separating presentation from content CSS Layout... lively exchange of information, resources, theories, and practices of designers and developers css- discuss.org (http://www .css- discuss.org/) This mailing list, which is chaperoned by CSS expert Eric Meyer, author of O’Reilly’s CSS: The Definitive Guide, aims to provide practical discussion about the application of CSS WebDesign-L.com (http://www.webdesign-l.com/) This mailing list has been around since... development CSS from the Ground Up” (http://www.wpdfd.com/editorial/basics/index.html) Web developers new to CSS will benefit from this well-paced tutorial available from Web Page Design for Designers “Basics of CSS Positioning” (http://www.communitymx.com/content/article.cfm?cid= 3B56F&print=true) For more information about positioning with CSS, try this tutorial by Community MX Floatutorial (http:/ /css. maxdesign.com.au/floatutorial/index.htm)... Resources A List Apart’s CSS Topics” (http://www.alistapart.com/topics/code /css/ ) At this website, most of the articles published on the topic of CSS come in from web designers sharing their thoughts and breakthroughs with CSS- enabled design Layout Reservoir (http://www.bluerobot.com/web/layouts/) This small but valuable resource from BlueRobot.com covers two- and threecolumn layouts CSS/ Edge (http://www.meyerweb.com/eric /css/ edge/)... reflections CSS 2D transforms CSS 3D transforms 14.13 Delivering HTML5 and CSS3 to Browsers That Can Handle Them | 643 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark • • • • • • • • • • • • • CSS transitions Geolocation API @font-face Canvas Canvas text HTML5 audio HTML5 video rgba() hsla() border-image: border-radius: box-shadow: Multiple backgrounds See Also The Modernizr documentation... about complex CSS selectors by translating their meaning into plain English CSS selectors can be submitted in one of two ways The first method is to copy and paste a CSS selector into the form The second method is to enter either a URL of a web page with an embedded stylesheet, or a URL to an external stylesheet The service then renders the CSS selector into easy-to-understand language W3C CSS Validator . following HTML5 and CSS3 features:
• opacity:
• CSS animations
• CSS columns
• CSS gradients
• CSS reflections
• CSS 2D transforms
• CSS 3D transforms
14.13. object:
$ (css- selector);
Then set a CSS selector within the jQuery object:
$("p+p");
Next, add the CSS declaration:
$("p+p") .css( "font-weight","normal");
jQuery