将CSS从JavaScript文件移出并移入CSS类

时间:2018-08-18 04:32:53

标签: javascript html css

我有以下JavaScript代码和内联CSS。

var container = display.getContainer();
container.style.cssText = 'width:100%;height:100%;z-index:100;object-fit: contain;';
document.body.appendChild(container);

我想将内联CSS移至style.css中的以下类

.containerClass {
    width:100%;
    height:100%;
    z-index:100;
    object-fit: contain;
}

我尝试了以下方法:

container.addClass('containerClass');

我无法正确表达我的问题,因此难以找到我要的精确解决方案。

进一步-我该如何告诉JavaScript文件.containerClass的位置?

2 个答案:

答案 0 :(得分:1)

在style.css中,定义react-native-sectioned-multi-select的属性。

style.css:

 import React, { Component } from 'react';
import { View } from 'react-native';
import { Container, Body, Header, Title, Content, List, ListItem, Text, Left, Right, Icon, Footer, FooterTab, Button} from 'native-base';
import SectionedMultiSelect from 'react-native-sectioned-multi-select';

var items = [];

class Home extends Component {
  constructor(){
    super();
    this.state = {
      data: [],
      selectedItems: []
    };
  }

  getData(){
    return fetch('https://test.com/php.php')
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(JSON.stringify(responseJson.result));
        this.setState({data:responseJson.result});
        //alert(responseJson.result[1].name);
        //return responseJson.result[1].name;
    })
    .catch((error) => {
      console.error(error);
    });
  }
  componentDidMount(){
    this.getData();

    this.state.data.map((cardData, i) =>{
        items.push({
              name: cardData.name,
              id: cardData.ver
        });
    });

  }
onSelectedItemsChange = selectedItems => {
    this.setState({ selectedItems });
  };


  render() {
    return (
      <View>

        <SectionedMultiSelect
          items={items} 
          uniqueKey='id'
          selectText='Choose some things...'
          showDropDowns={false}
          readOnlyHeadings={false}
          onSelectedItemsChange={this.onSelectedItemsChange}
          selectedItems={this.state.selectedItems}
        />

      </View>
    );
  }
}

要添加此样式时,只需将该类添加到要使用javascript的元素中即可。 Javascript:

result [{
   name: xxxxxx,
   ver: xxxxx
}]

答案 1 :(得分:1)

  

注意: Internet Explorer 9不支持 classList 属性。

以下代码将在所有浏览器中运行-

function addClass() {
  var element, name, arr;
  element = document.getElementById("container");
  name = "mystyle";
  arr = element.className.split(" ");
  if (arr.indexOf(name) == -1) {
    element.className += " " + name;
  }
}
.mystyle {
  background-color: black;
  color: white;
}

div {
  margin-top: 20px;
  width: 100%;
  padding: 25px;
  font-size: 25px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<p>Click the "Add Class" button to add the "mystyle" class to the container element:</p>

<button onclick="addClass()">Add Class</button>

<div id="container">This is a DIV element.</div>