简体   繁体   English

如何将CSS和javascript转换为类

[英]How to convert a CSS and a javascript to a class

I have some problems converting the CSS id to a class and the javascript to match it. 我有一些问题将CSS ID转换为类和javascript以匹配它。 I need to use the script multiple times on the site 我需要在网站上多次使用该脚本

Here my code: CSS: 这里是我的代码:CSS:

#first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
} 

JavaScript: JavaScript的:

var divh = document.getElementById('first').offsetHeight;

//keep default height
var divh = $("#first").outerHeight();

document.getElementById("first").style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $("#first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $("#first").stop().animate({
      height: '100px'
    }, 1000);
  }
)

If I understand correctly you can just do: 如果我理解正确你可以这样做:

.first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
}

And the Javascript would be something like this: 而Javascript将是这样的:

var divh = $('.first').offsetHeight;

//keep default height
var divh = $(".first").outerHeight();

$('.first').style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $(".first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $(".first").stop().animate({
      height: '100px'
    }, 1000);
  }
)

Just uses the jQuery selector to select the class instead of the ID. 只需使用jQuery选择器来选择类而不是ID。

I think you can use a " class selector " to get all the elements belonging to that class and then apply animation to all of them or one by one by using the each function (see here ). 我认为你可以使用“ 类选择器 ”来获取属于该类的所有元素,然后通过使用each函数将动画应用于所有元素或逐个应用(参见此处 )。 Something like: 就像是:

CSS CSS

.first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
} 

JavaScript: JavaScript的:

$('.first').each(function () {
    var divh = $(this).outerHeight();
    ecc. ecc.
})

使用#first。 首先瞬间

Mark's answer is almost entirely correct. 马克的答案几乎完全正确。

Although, he changed $('div:first') to $('div.first') which are not the same thing. 虽然,他将$('div:first')更改为$('div.first')并不是同一回事。

:first is part of jQuery selectors to select only the first matched element (see here ). :首先是jQuery选择器的一部分,只选择第一个匹配的元素(见这里 )。

So, if you want to pick the first div, use $('div:first'). 所以,如果你想选择第一个div,请使用$('div:first')。 If you want to select all divs with the "first" class, use $('div.first'). 如果要选择具有“first”类的所有div,请使用$('div.first')。

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

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