简体   繁体   English

根据文本换行和 window 宽度(Jquery 或 JavaScript)更改 CSS class

[英]Changing a CSS class depending on text wrap and window width (Jquery or JavaScript)

I have a responsive design with some text columns.我有一个带有一些文本列的响应式设计。 The columns have h2 headings and floated to the left of the headings are image icons - nicely vertically centered to the heading text.这些列有 h2 标题,浮动在标题左侧的是图像图标——很好地垂直居中于标题文本。 The problem occurs when I narrow the window width.当我缩小 window 宽度时出现问题。 When the single heading lines wrap, they are no longer vertically aligned to the icons.当单个标题行换行时,它们不再与图标垂直对齐。

Basically, I'm trying to write a script that tells the class of the heading to change when it wraps to two lines so that I can alter the vertical position of it to be centered.基本上,我正在尝试编写一个脚本,告诉标题的 class 在它换行成两行时进行更改,以便我可以将其垂直方向的 position 更改为居中。

I'm really new to scripting so I'm not sure how to write it but this is essentially it:我真的是脚本新手,所以我不确定如何编写它,但这基本上就是这样:

if window width > 768 and if lines of text in #services h2 = 1

#services h2 {
top:9px;
}

else

if window width > 768 and if lines of text in #services h2 > 1

#services h2 {
top:1px;
}

Could someone help me properly format this?有人可以帮我正确格式化吗? I'm already using jQuery for some other stuff so if it's possible to do it with that, that would be great.我已经将 jQuery 用于其他一些东西,所以如果可以用它来做,那就太好了。

Thanks!谢谢!

EDIT: The most important part of this is the changing of a class property when a line wraps from 1 line to 2. This is the critical part:编辑:其中最重要的部分是当一行从 1 行换行到 2 行时更改 class 属性。这是关键部分:

if lines of text in #services h2 = 1

#services h2 {
top:9px;
}

else

if lines of text in #services h2 > 1

#services h2 {
top:1px;
}

Could you not just set the vertical position of background image to be 50%?你能不能把背景图片的垂直position设置为50%? Rather than adding js to a relatively minor cosmetic change.而不是将 js 添加到相对较小的外观更改中。

No JavaScript (includes jQuery) needed, use pure CSS: http://www.css3.info/preview/media-queries/ .不需要 JavaScript(包括 jQuery),使用纯 CSS: http://www.css3.info/preview/media-queries/

A longer explanation can be found at http://css-tricks.com/css-media-queries/可以在http://css-tricks.com/css-media-queries/找到更长的解释

I am not sure about the 'and if lines of text' but the left side of the AND, would be:我不确定'and if lines of text'但AND的左侧是:

-EDIT- I see, let see if this is what you want. -编辑- 我明白了,让我们看看这是否是您想要的。

$(window).resize(function(){
     var h =$('#services h2').css('line-height');
     var size = $(window).width();
     if (size > 768){
          if( $('#services h2').height() == h){
                 $('#services h2').css('top','1px')
          }
     }else{
           if( $('#services h2').height() > 2*h){
                 $('#services h2').css('top','9px')
          }
     }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM