window.resize
是正确的事件,但它不会在页面加载时触发。但是您可以只添加.trigger('resize')
添加到您的代码以使其在页面加载时触发:
$(window).bind('resize', function(){
var containerSize = $('.container').width(),
textPercentage = 0.17391304347826086956521739130435, /* 40/230 */
textRatio = containerSize * textPercentage,
textEms = textRatio / 14;
$('.container h3').css(fontSize, textEms+"em");
}).trigger('resize');
您将需要在之后运行此代码document.ready
确保您获得的容器宽度是正确的。您还可以将此代码放在 HTML 文档的底部(您应该使用或不使用document.ready
事件处理程序),这将确保运行此代码时元素可用:
//wait for `document.ready` to fire
$(function () {
//cache the .container and H3 elements
var $container = $('.container'),
$h3 = $container.find('h3');
//bind event handler to `window.resize`
$(window).bind('resize', function(){
//get the width of the container
var containerSize = $container.width(),
textPercentage = 0.17391304347826086956521739130435, /* 40/230 */
textRatio = containerSize * textPercentage,
textEms = textRatio / 14;
$h3.css('fontSize', textEms+"em");
}).trigger('resize');
});
请注意,我缓存了H3
元素,因此不必每次都选择它/然后resize
事件,因为当您实际调整浏览器大小时,会触发大量此类事件。