Javascript:如何单击按钮,显示某些内容,然后再次单击并返回默认值?

时间:2021-06-16 08:25:02

标签: javascript html jquery css

我有一个小问题:我有一些使用 CSS 样式化的 HTML 内容。我在 JS 中创建了一个函数,当我点击一个按钮时,内容被修改。我希望再次单击按钮并显示默认内容(HTML + CSS),某种“回归基本”。在没有在 CSS 中创建类和使用切换或不刷新页面的情况下,这样做的方法是什么?很简单:点击--> 显示JS 中所做的更改,再次点击--> 消失JS 中所做的更改。谢谢!

var switchStatus = false;
$("#switch-button").on("click", function() {
  if(switchStatus === false) {
    $("body").css("background-color", "white");
    $("h1").css("color", "#24242e");
    $(".followers").css("color", "#67627b");
    $(".switch-text").css("color", "#67627b");
    $("#switch-button").css({
      "background-color": "#252b43",
      "color": "lightgrey"
      }).text("Dark Mode");
    $(".my-card").css("background-color", "#f0f3fa");
    $(".card-user").css("color", "#252b43");
    $("h5").css("color", "#252b43");
    $("h2").css("color", "#252b43");
    $(".secondLineCard").css("background-color", "#f0f3fa");
    $(".small-card-actions").css("color", "grey");
    $(".small-card-number").css("color", "#24242e");
    switchStatus = true;
  } else if(switchStatus === true) {
    //What piece of code should I put here to get back to normal content without refreshing the page?
  }
});

1 个答案:

答案 0 :(得分:2)

这就是你想要做的。

dataframe= pd.read_csv('data.csv')
creat_plot(dataframe)
import pandas as pd
from bokeh.plotting import figure
from bokeh.io import show,output_file
from bokeh.models import CustomJS,HoverTool,ColumnDataSource,Select
from bokeh.models.widgets import CheckboxGroup
from bokeh.models.annotations import Title, Legend
import itertools
from bokeh.palettes import inferno
from bokeh.layouts import row

def creat_plot(dataframe):
    data=dataframe
    #Converting the timestamp Column to Timestamp datatype so that it can be used for Plotting on X-axis
    data['timestamp'] = pd.to_datetime(data['timestamp'])
    
    #Segregating Date and Time from timestamp column. It will be used in Hover Tool
    date = lambda x: str(x)[:10]
    data['date'] = data[['timestamp']].applymap(date)
    time= lambda x: str(x)[11:]
    data['time'] = data[['timestamp']].applymap(time)
    
    #Converting whole dataframe ColumnDatasource for easy usage in hover tool
    source = ColumnDataSource(data)
    
    # List all the tools that you want in your plot separated by comas, all in one string.
    TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover"
    
    # New figure
    t = figure(x_axis_type = "datetime", width=1500, height=600,tools=TOOLS,title="Plot for Interactive Visualization")
    
    #X-axis Legend Formatter
    t.xaxis.formatter.days = '%d/%m/%Y'
    
    #Axis Labels
    t.yaxis.axis_label = 'Count'
    t.xaxis.axis_label = 'Date and Time Span'
    
    #Grid Line Formatter
    t.ygrid.minor_grid_line_color = 'navy'
    t.ygrid.minor_grid_line_alpha = 0.1
    t.xgrid.visible = True
    t.ygrid.visible= True
    
    #Hover Tool Usage
    t.select_one(HoverTool).tooltips = [('Date', '@date'),('Time', '@time')]
    
    #A color iterator creation
    colors = itertools.cycle(inferno(len(data.columns)))
    
    #A Line type iterator creation
    line_types= ['solid','dashed','dotted','dotdash','dashdot']
    lines= itertools.cycle(line_types)
    
    feature_lines = []
    column_name=[]
    #Looping over the columns to plot the Data
    for m in data.columns[2:len(data.columns)-2]:
        column_name.append(m)
        #Solution to my question is here
        feature_lines.append(t.line(data.columns[0], m ,color=next(colors),source=source,line_dash=next(lines), alpha= 1, visible=False))
        
         
    #Adding Label Selection Check Box List
    column_name= list(column_name)
    
   #Solution to my question, 
    checkbox = CheckboxGroup(labels=column_name, active=[])
    #Solution to my question
    callback = CustomJS(args=dict(feature_lines=feature_lines, checkbox=checkbox), code="""
                                                            for (let i=0; i<feature_lines.length; ++i) {
                                                                feature_lines[i].visible = i in checkbox.active
                                                            }
                                                            """)
    checkbox.js_on_change('active', callback)
    output_file('Interactive_data_visualization.html')
    show(row(t, checkbox))

更好的方法是使用带有 **let idx = 1; const scrollRef = React.useRef(); const onPressHandler = () => { scrollRef.current.scrollToIndex({index:idx,animated:true}); };** return ( <SafeAreaView style={styles.container}> <ScrollView **ref={scrollRef}** pagingEnabled horizontal scrollEventThrottle={16} showsHorizontalScrollIndicator={false} onScroll={Animated.event([ { nativeEvent: { contentOffset: { x: animation, } }, **{ useNativeDriver:false, listener: event => { const offsetX = event.nativeEvent.contentOffset.x; console.log(offsetX); idx = offsetX/screenWidth; idx += 1; } }** } ])} > <View style={{ width }}> <Text>First Page</Text> <Button title="Next" onPress={onPressHandler} /> </View> <View style={{ width }}> </View> </ScrollView> </SafeAreaView> ) 的 css 类

let switchStatus = true;

$("#switch-button").on("click", function () {
  if (switchStatus === false) {
    $("body").css("background-color", "white");
    switchStatus = true;
  } else if (switchStatus === true) {
    $("body").css("background-color", "blue");
    switchStatus = false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<button id="switch-button">switch</button>
</body>
toggleClass()