哪个css选择器可以定位具有多个类的元素?

时间:2017-06-26 19:12:34

标签: css css-selectors

我不确定如何正确地标出标题,但我有一个div列表,还有一些还有.active的额外类。我只需要定位第一个和最后一个,但我尝试的每个选择器都与所有项目共享的类相关,即.item所以我无法达到我想要的效果。

.active:first-child {
  background-color: blue;
}

.active:last-child {
  background-color: blue;
}

.active:nth-child(odd) {
  background-color: green;
}

.active:nth-of-type(odd) {
  background-color: yellow;
}
<div class="item-container">
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
</div>

这些都不起作用。我一直在弄乱它:https://jsfiddle.net/f0226073/2/

修改 所以我应该澄清一下。我正在使用Owl Carousel并且每张幻灯片显示3个项目。可以存在更多.item div,但总会有3个.active div。选择器需要是动态的,如果添加了更多.item,那么这不会影响.active div选择器。

2 个答案:

答案 0 :(得分:1)

.item:not(.active) + .active {
  background-color: aqua;
}
.active + .active + .active {
  background-color: aqua;
}
.active:first-child { /* in case .active is ever the first child */
  background-color: aqua;
}
<div class="item-container">
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
</div>

由于总会有三个.active元素,并且它们将始终是连续的,因此第一个选择器将匹配第一个.active,第二个选择器将匹配第三个.active。如果.item:not(.active) + .active, .active + .active + .active, .active:first-child { background-color: aqua; }是所有兄弟姐妹中的第一个,则可以使用第三个选择器。

此外,假设样式相同,可以将三个选择器合并为一个:

<div class="item-container">
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
</div>
//
//  ViewController.swift
//  speech_sample
//
//  Created by Peizheng Ma on 6/22/17.
//  Copyright © 2017 Peizheng Ma. All rights reserved.
//

import UIKit
import AVFoundation
import Speech

class ViewController: UIViewController, SFSpeechRecognizerDelegate {

//MARK: speech recognize variables
let audioEngine = AVAudioEngine()
let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
var request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?
var isRecording = false

override func viewDidLoad() {
    // super.viewDidLoad()
    // get Authorization
    self.requestSpeechAuthorization()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: properties
@IBOutlet weak var detectText: UILabel!
@IBOutlet weak var startButton: UIButton!

//MARK: actions
@IBAction func startButtonTapped(_ sender: UIButton) {
    if isRecording == true {


        audioEngine.stop()
//            if let node = audioEngine.inputNode {
//                node.removeTap(onBus: 0)
//            }
        audioEngine.inputNode?.removeTap(onBus: 0)
        // Indicate that the audio source is finished and no more audio will be appended
        self.request.endAudio()

        // Cancel the previous task if it's running
        if let recognitionTask = recognitionTask {
            recognitionTask.cancel()
            self.recognitionTask = nil
        }


        //recognitionTask?.cancel()
        //self.recognitionTask = nil
        isRecording = false
        startButton.backgroundColor = UIColor.gray
    } else {
        self.recordAndRecognizeSpeech()
        isRecording = true
        startButton.backgroundColor = UIColor.red
    }
}

//MARK: show alert
func showAlert(title: String, message: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) {
    DispatchQueue.main.async { [unowned self] in
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: handler))
        self.present(alertController, animated: true, completion: nil)
    }
}

//MARK: Recognize Speech
func recordAndRecognizeSpeech() {
    // Setup Audio Session
    guard let node = audioEngine.inputNode else { return }
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        self.showAlert(title: "SpeechNote", message: "There has been an audio engine error.", handler: nil)
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not supported for your current locale.", handler: nil)
        return
    }
    if !myRecognizer.isAvailable {
        self.showAlert(title: "SpeechNote", message: "Speech recognition is not currently available. Check back at a later time.", handler: nil)
        // Recognizer is not available right now
        return
    }
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {

            let bestString = result.bestTranscription.formattedString
            self.detectText.text = bestString

//                var lastString: String = ""
//                for segment in result.bestTranscription.segments {
//                    let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
//                    lastString = bestString.substring(from: indexTo)
//                }
//                self.checkForColorsSaid(resultString: lastString)
        } else if let error = error {
            self.showAlert(title: "SpeechNote", message: "There has been a speech recognition error.", handler: nil)
            print(error)
        }
    })
}

//MARK: - Check Authorization Status
func requestSpeechAuthorization() {
    SFSpeechRecognizer.requestAuthorization { authStatus in
        OperationQueue.main.addOperation {
            switch authStatus {
            case .authorized:
                self.startButton.isEnabled = true
            case .denied:
                self.startButton.isEnabled = false
                self.detectText.text = "User denied access to speech recognition"
            case .restricted:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition restricted on this device"
            case .notDetermined:
                self.startButton.isEnabled = false
                self.detectText.text = "Speech recognition not yet authorized"
            }
        }
    }
}


}

答案 1 :(得分:0)

.active div的第一个和最后一个:

HTML

<div class="item-container">
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item active">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
  <div class="item">123</div>
</div>

CSS

.active:nth-of-type(2n + 1) {
  background-color: red;
}

小提琴:https://jsfiddle.net/dt0qw3kv/2/